[英]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>
}
If I want 'thing' to be passed from parent to child but not update when parent changes it, how do I accomplish this?如果我希望“事物”从父级传递给子级,但在父级更改时不更新,我该如何实现?
I've tried useEffect, tried cloning 'thing' to a constant within Child...我尝试过 useEffect,尝试将“事物”克隆到 Child 中的常量...
I would use useEffect
with the empty []
for dependencies, so that it only runs once.我会使用
useEffect
和空的[]
作为依赖项,以便它只运行一次。
From Reactjs.org :来自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.这告诉 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>
);
};
Maybe you can try setting the thing to a variable in the child component when it's null.当它是 null 时,也许您可以尝试将其设置为子组件中的变量。 So when the parent update, you don't have to update the child.
因此,当父更新时,您不必更新子。
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.