React: Update Child Component Without Rerendering Parent

后端 未结 2 897
一生所求
一生所求 2021-02-13 20:39

What follows is a simple example:

<
2条回答
  •  借酒劲吻你
    2021-02-13 21:30

    When you want to update a child without updating the parent, the state must be in the child. You can pass the state getter / setter from the child to the parent to be able to read and update it:

    function Child({onMount}) {
      const [value, setValue] = useState(0);
    
      useEffect(() => {
        onMount([value, setValue]);
      }, [onMount, value]);
    
    
      return (
        
    {value}
    ); }; function Parent() { let value = null; let setValue = null; const onChildMount = (dataFromChild) => { value = dataFromChild[0]; setValue = dataFromChild[1]; }; // Call setValue to update child without updating parent return (
    ); };

    Since const [value, setValue] = useState(0); is in the Child, only the child component will re render when updating the value. Additionally, since the Parent receives value and setValue at onChildMount, the parent can use them to update the child without re rendering the parent.

提交回复
热议问题