在useCallback挂钩中反应setState不能正确设置状态变量?

问题描述

我在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 />;

在上面的代码中,具有someAttribute的someArray元素始终存在匹配项。 但是问题是MyComponent始终呈现ComponentNotFound,因为isFound总是在最后一行(返回语句)的值为FALSE。

我能够通过以下重构来解决此问题(插入一个中间变量,但总体逻辑保持不变):

const MyComponent: React.FunctionComponent<ISomeInterface> = ({ someArray,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 />;

使用此代码的第二版,isFound在最后一行正确求值为TRUE,而MyComponent正确呈现FoundMatchingComponent。

您能否解释一下为什么第一个版本不起作用而第二个版本不起作用?

我的猜测是第二个版本中的中间变量为React提供了足够的时间在return语句中正确评估isFound变量,但是我不确定这是解释。任何改进我上面代码的建议也将不胜感激。谢谢。

解决方法

在第一个代码段中,我看不到someStateVar的定义位置。如果是这种情况,则变量为undefined,因此setIsFound(someStateVar ?? false)将始终评估为false。因此,isFound为假,并且return语句将始终返回<ComponentNotFound />

您打算拥有setIsFound(someStateObjVar ?? false)吗?

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...