简体   繁体   English

useState 不会立即通过双击更新 state

[英]useState doesn't update state by double click immediately

I am trying to get info from an api but the useState() doesn't work correctly.我正在尝试从 api 获取信息,但 useState() 无法正常工作。 I have a work order grid by double click on each row I get the work order id then I should get the information from a specific api route to "workorder/:id" and display them.我有一个工作订单网格,双击每一行我得到工作订单 ID,然后我应该从特定的 api 路由到“workorder/:id”获取信息并显示它们。 but when I try to console log the information by double click on a row I get "undefined"但是当我尝试通过双击一行来控制台记录信息时,我得到“未定义”

here is my code:这是我的代码:

  const gridOptions = {
    onRowDoubleClicked: openWorkOrder,
  }
function openWorkOrder(row) {
        const workOrderId = row.data.id
        navigate(`workorder/${workOrderId}`)
        fetch(`baseURL/api/Gages/WorkFlow/GetProductDetailByOrderId?id=${workOrderId}`)
          .then((result) => result.json())
          .then((data) => props.setDetails(data))
        console.log(props.details)
    } 

const [details, setDetails] = useState() is defined in the parent component. const [details, setDetails] = useState()在父组件中定义。

The useState in React is an asynchronous hook ( Reference ). React 中的useState是一个异步钩子(参考资料)。 When you call useState, it doesn't update state immediately.当您调用 useState 时,它不会立即更新 state。

If you want to get updated state, you must use useEffect hook.如果你想获得更新 state,你必须使用useEffect hook。

import { useEffect } from "react";


useEffect(() => {
    console.log(details)
},[details]);

For more Detail about React useEffect hook refer to documentation有关 React useEffect hook 的更多详细信息,请参阅文档

Also Refer to Is setState() method async?另请参阅setState() 方法是否异步? and Change is not reflected and await useState in React for more detail并且更改未反映等待 React 中的 useState 以获取更多详细信息

The function returned by useState does not update the state immediately. useState 返回的useState不会立即更新 state。 Instead, it tells React to queue a state update, and this will be done once all event handlers have run.相反,它告诉 React 对 state 更新进行排队,这将在所有事件处理程序运行后完成。

Once the component is re-rendered, you will then see the new state.重新渲染组件后,您将看到新的 state。

When you console.log right after the fetch, the component has not yet re-rendered, and hence you see undefined .当您在获取后立即使用console.log时,组件尚未重新呈现,因此您会看到undefined

Fetch is async , and you placed console.log() after it, so there are no props.details at this moment. Fetch 是async ,你在它之后放置了console.log() ,所以此时没有props.details You can try to convert openWorkOrder to async function and await for fetched results.您可以尝试将openWorkOrder转换为async function 并await获取的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM