簡體   English   中英

在 useCallback() 鈎子中反應 setState 沒有正確設置狀態變量?

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

我在 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 變量,但我不相信這是解釋。 任何關於改進我上面代碼的建議也將不勝感激。 謝謝。

在第一個代碼片段中,我沒有看到someStateVar的定義位置。 如果是這種情況,變量是undefined ,所以setIsFound(someStateVar ?? false)將始終評估為 false。 因此, isFound為 false 並且 return 語句將始終返回<ComponentNotFound />

您是否打算使用setIsFound(someStateObjVar ?? false)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM