componentWillReceiveProps, componentDidUpdate for React Hook

后端 未结 8 1175
闹比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
    慢半拍i (楼主)
    2020-12-25 11:14

    In your scenario, you don't need to use or re-implement getDerivedStateFromProps at all. You just need to create a new variable to get the new form of data. Using state in this scenario will just cause another re-rendering which is not good performance wise.

    import React from 'react';
    
    const App = ({ count }) => {
      const derivedCount = count > 100 ? 100 : count;
    
      return (
        
    Counter: {derivedCount}
    ); } App.propTypes = { count: PropTypes.number.isRequired }

    Demo here: https://codesandbox.io/embed/qzn8y9y24j?fontsize=14

    You can read more on different ways to solve these kind of scenarios without using getDerivedStateFromProps here: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html

    If you really need to use a separate state, you can use something like this

    import React, { useState } from 'react';
    
    const App = ({ count }) => {
      const [derivedCounter, setDerivedCounter] = useState(
        count > 100 ? 100 : count
      );
    
      useEffect(() => {
        setDerivedCounter(count > 100 ? 100 : count);
      }, [count]); // this line will tell react only trigger if count was changed
    
      return 
    Counter: {derivedCounter}
    ; };

提交回复
热议问题