![](/img/trans.png)
[英]Using React Hooks, when I pass down a prop from parent to a child component, the prop in the child component is undefined
[英]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.