1

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

在上面的代码中,someArray 元素总是与 someAttribute 匹配。但问题是 MyComponent 总是呈现 ComponentNotFound 因为 isFound 在最后一行(返回语句)总是评估为 FALSE。

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

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

使用此代码的第二个版本,isFound 在最后一行正确评估为 TRUE,并且 MyComponent 正确呈现 FoundMatchingComponent。

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

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

4

1 回答 1

0

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

你打算有setIsFound(someStateObjVar ?? false)吗?

于 2020-12-14T17:44:00.097 回答