简体   繁体   English

在 useCallback() 钩子中反应 setState 没有正确设置状态变量?

[英]React setState inside useCallback() hook not setting state variable correctly?

I have code that is of the following pattern inside a React FunctionComponent:我在 React FunctionComponent 中有以下模式的代码:

const MyComponent: React.FunctionComponent<ISomeInterface> = ({ someArray, someFunction }) => {

  const [someStateObjVar, setSomeStateObjVar] = React.useState({});
  const [isFound, setIsFound] = React.useState(false);

  const handleSomeEvent = React.useCallback((someAttribute: string) => {
    if (someAttribute) {
      setSomeStateObjVar(someArray.find(
        (arrayElement) => ( arrayElement.attribute === someAttribute )
      );
      setIsFound(someStateVar ?? false);
    }
  }
  
  return ( isFound && someStateObjVar ) ? <FoundMatchingComponent /> ? <ComponentNotFound />;

In the above code, there's always a match for someArray element with someAttribute.在上面的代码中,someArray 元素总是与 someAttribute 匹配。 But the problem is MyComponent always renders ComponentNotFound because isFound always evaluates to FALSE at the last line (return statement).但问题是 MyComponent 总是呈现 ComponentNotFound 因为 isFound 在最后一行(返回语句)总是评估为 FALSE 。

I was able to fix this with the following refactor below (inserting an intermediate variable, but overall the logic remains the same):我能够通过以下重构来解决这个问题(插入一个中间变量,但总体逻辑保持不变):

const MyComponent: React.FunctionComponent<ISomeInterface> = ({ someArray, someFunction }) => {

  const [someStateObjVar, setSomeStateObjVar] = React.useState({});
  const [isFound, setIsFound] = React.useState(false);

  const handleSomeEvent = React.useCallback((someAttribute: string) => {
    let foundElement;
    if (someAttribute) {
      foundElement = someArray.find(
        (arrayElement) => ( arrayElement.attribute === someAttribute )
      );
    }
    if (foundElement) {
      setSomeStateObjVar(foundElement);
      setIsFound(true);
    }
  }
  
  return ( isFound && someStateObjVar ) ? <FoundMatchingComponent /> ? <ComponentNotFound />;

With this 2nd version of the code, isFound correctly evaluates to TRUE at the last line, and MyComponent correctly renders FoundMatchingComponent.使用第二个版本的代码,isFound 在最后一行正确评估为 TRUE,并且 MyComponent 正确呈现 FoundMatchingComponent。

Can you please provide an explanation why the first version does not work, while the second one does?您能否解释为什么第一个版本不起作用而第二个版本起作用?

My guess is that the intermediate variable in the second version gives enough time for React to evaluate the isFound variable correctly at the return statement, but I'm not confident this is the explanation.我的猜测是第二个版本中的中间变量为 React 提供了足够的时间在 return 语句中正确评估 isFound 变量,但我不相信这是解释。 Any advice on improving my code above would be appreciated as well.任何关于改进我上面代码的建议也将不胜感激。 Thanks.谢谢。

In the first code snippet, I do not see where someStateVar is defined.在第一个代码片段中,我没有看到someStateVar的定义位置。 If that is the case the variable is undefined , so setIsFound(someStateVar ?? false) will always evaluate as false.如果是这种情况,变量是undefined ,所以setIsFound(someStateVar ?? false)将始终评估为 false。 Therefore, isFound is false and the return statement will always return <ComponentNotFound /> .因此, isFound为 false 并且 return 语句将始终返回<ComponentNotFound />

Did you intend to have setIsFound(someStateObjVar ?? false) ?您是否打算使用setIsFound(someStateObjVar ?? false)

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

相关问题 setState没有设置状态变量React - setState not setting state variable React React Native:state 在 useCallBack 钩子 function 内变得未定义 - React Native : state is getting undefined inside useCallBack hook function 反应无法在promise内使用setState正确更新状态 - React not updating state with setState correctly inside promises 自定义挂钩 useEffect 内的 React setState 调用未更新 state - React setState call inside a custom hook useEffect is not updating the state 在React Hook的setState()调用中访问当前状态时,prevState变量是副本还是对状态对象的直接引用? - When accessing the current state inside a React Hook's setState() call, is the prevState variable a copy or a direct reference to the state object? 反应 | UseCallBack 内的道具未在自定义挂钩内更新 - React | props inside UseCallBack not updating inside custom hook 反应 useCallback 钩子,没有收到更新的依赖 state 值 - React useCallback hook, not receiving updated dependency state value 调用时 React Hook useCallback 未更新 state - React Hook useCallback not getting updated state when invoked 反应:正确的 state 突变与 setState 挂钩 - React: Proper state mutation with setState hook 反应钩子 - setState 没有更新 state - React hook - setState didn't update state
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM