我有预订应用程序.如果用户点击预订详细信息BTN,用户可以看到数据.已提取数据,但useEffect不满意.

UseEffect向我显示此错误消息: Reaction Hook React.useEffect缺少依赖项:‘getDetail’.包括它或删除依赖项array.

我不能删除依赖数组,它给出了无限循环,对吗?那么,如何解决这个问题呢? 我试着把我所有的东西都放在那里,但还是有黄色下划线.


const BookedDetails = () => {

  const { user } = useSelector((state) => state.userAuth)
  const userID = user?.user?._id

  const [details, setDetails] = React.useState([])
  const [loading, setLoading] = React.useState(false)
  const [invoiceLoad, setInvoiceLoad] = React.useState(false)
  const [currentPage, setCurrentPage] = React.useState(1)
  const [postPerPage, setPostPerPage] = React.useState(4)

  const indexOfLastPost = currentPage * postPerPage
  const indexOfFirstPost = indexOfLastPost - postPerPage
  const currenPosts = details.slice(indexOfFirstPost, indexOfLastPost)

 const pages = []

 for(let i = 1; i <= Math.ceil(details.length / postPerPage); i++) {
  pages.push(i)
 }

 const paginate = (x) => {
    setCurrentPage(x)
 }


  const getDetails = async () => {

    const config = {
        headers: {
          "Content-Type": "application/json",
        }
      }

    try {
      setLoading(true)
      const res = await axios.post('/api/bookingDetails/bookDetails', { userID }, config )     
      //console.log(res.data.user)
      setDetails(res.data.user)
      setLoading(false)

    } catch (error) {
      console.log(error.message)
      setLoading(false)
    }
  }

  React.useEffect(() => {
    getDetails()
  },[ ])    //  << dependency is yellow underlined.

推荐答案

您可以在useEffect钩子中定义getDetails方法.

例如:

React.useEffect(() => {
  const getDetails = async () => {
    const config = {
      headers: {
        "Content-Type": "application/json",
      },
    };

    try {
      setLoading(true);
      const res = await axios.post(
        "/api/bookingDetails/bookDetails",
        { userID },
        config
      );

      setDetails(res.data.user);
      setLoading(false);
    } catch (error) {
      console.log(error.message);
      setLoading(false);
    }
  };

  getDetails();
}, [userID]);

Reactjs相关问答推荐

Shadck/ui Select -当用户 Select 项目时更改状态

构建next.js项目时状态不变,但在dev服务器中

Reaction Native:在初始获取后,Reducer变为未定义

导致useState中断的中断模式

这两个子元素在Reaction Native中使用的有什么不同?

在React中映射对象数组时,如何正确呈现JSX.Element或React.ReactNode类型?

根据处于react 状态的数组的名称键,将新对象添加到嵌套的对象数组中

在迭代状态时无法读取未定义的属性(读取 map )

通过createRoot创建的React元素无法调用Provider值

React useEffect 依赖项

未处理的拒绝 (TypeError):无法读取未定义的属性(读取协议)

将水平滚动视图添加到底部导航选项卡

使用登录保护 React 中的 SPA 应用程序 - 为什么这种方法不起作用?

图像路径很奇怪,部署 Next.js 应用程序后我看不到任何图像

React - 添加了输入数据但不显示

React Native - 身份验证 - 触发值以更改 Auth 和 UnAuth 堆栈导航器

如何解决在 react.js 中找不到模块错误

如何解决在 react.js 中找不到模块错误

如何将 id 从页面传递到另一个页面?

React Router 6,一次处理多个搜索参数