簡體   English   中英

如何在父項更改時將道具傳遞給反應組件但不更新子項中的該道具?

[英]How do I pass a prop to a react component yet not update that prop in the child when parent changes?

const Parent = () => {
   const [thing, setThing] = useState('a string');

   // code to update thing

   return <Child thing={thing} />
}

const Child = props => {
   return <div>I want {props.thing} to be initial value without updating</div>
}

如果我希望“事物”從父級傳遞給子級,但在父級更改時不更新,我該如何實現?

我嘗試過 useEffect,嘗試將“事物”克隆到 Child 中的常量...

我會使用useEffect和空的[]作為依賴項,以便它只運行一次。

來自Reactjs.org

如果你想運行一個效果並且只清理一次(在掛載和卸載時),你可以傳遞一個空數組( [] )作為第二個參數。 這告訴 React 你的效果不依賴於 props 或 state 的任何值,所以它永遠不需要重新運行。

const Child = props => {
  let thing = props.thing;
  let [initialValue, setInitialValue] = useState("");

  useEffect(() => {
    setInitialValue(thing);
  }, []);

  return (
    <div>
      I want <strong>{initialValue}</strong> to be initial value without
      updating
    </div>
  );
};

在此處輸入圖像描述

代碼沙盒

當它是 null 時,也許您可以嘗試將其設置為子組件中的變量。 因此,當父更新時,您不必更新子。

let childThing = null;
const Child = props => {
   if(childThing === null)
       childThing = props.thing
   return <div>I want {childThing} to be initial value without updating</div>
}

暫無
暫無

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

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