简体   繁体   中英

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...

I would use useEffect with the empty [] for dependencies, so that it only runs once.

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

在此处输入图像描述

CodeSandbox

Maybe you can try setting the thing to a variable in the child component when it's 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>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM