gpt4 book ai didi

javascript - 当父级更改时,如何将 Prop 传递给 react 组件但不更新子级中的 Prop ?

转载 作者:行者123 更新时间:2023-12-04 10:07:03 24 4
gpt4 key购买 nike

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 :

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.



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>
);
};

enter image description here

CodeSandbox

关于javascript - 当父级更改时,如何将 Prop 传递给 react 组件但不更新子级中的 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61534029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com