componentWillReceiveProps, componentDidUpdate for React Hook

后端 未结 8 1180
闹比i
闹比i 2020-12-25 11:00

I run into two challenges:

  • Even if, as per React guideline, derived state is discouraged, but some edge cases still need it.
    In terms of
8条回答
  •  旧时难觅i
    2020-12-25 11:11

    1.) What is the equivalent implementation with React Hook, If I do need derived state?

    Derived state for Hooks = set state conditionally and directly in the render phase:

    constComp = (props) => {
      const [derivedState, setDerivedState] = useState(42);
      if (someCondition) {
        setDerivedState(...);
      }
      // ...
    }
    

    This updates state without an additional commit phase as opposed to useEffect. Above pattern is supported by React Strict Mode (no warnings):

    const App = () => {
      const [row, setRow] = React.useState(1);
    
      React.useEffect(() => {
        setTimeout(() => {
          setRow(2);
        }, 3000);
      }, []);
    
      return (
        
          
        
      );
    }
    
    const Comp = ({ row }) => {
      const [isScrollingDown, setIsScrollingDown] = React.useState(false);
      const [prevRow, setPrevRow] = React.useState(null);
    
      console.log("render, prevRow:", prevRow)
    
      if (row !== prevRow) {
        console.log("derive state");
        // Row changed since last render. Update isScrollingDown.
        setIsScrollingDown(prevRow !== null && row > prevRow);
        setPrevRow(row);
      }
    
      return `Scrolling down: ${isScrollingDown}`;
    };
    
    ReactDOM.render(, document.getElementById("root"));
    
    
    

    Note 1: componentWillReceiveProps has been deprecated for quite some time. getDerivedStateFromProps is the class components' successor in terms of derived state.

    Note 2: Check preferred solutions before you resort to derived state.


    2.) What if I want to do respective tasks based on multiple respective props changes?

    You can either leave useEffect deps out completely or preferably add another prop dep:

    React.useEffect(() => {
      return () => { };
    }, [parentProp, secondProp]);
    

提交回复
热议问题