代码之家  ›  专栏  ›  技术社区  ›  JoeTidee

react-GetDerivedStateFromProps是否需要返回所有状态属性?

  •  3
  • JoeTidee  · 技术社区  · 6 年前

    当使用 getDerivedStateFromProps React组件中的Lifecycle方法,返回的状态是完全覆盖组件的现有状态,还是只是更新返回的特定状态属性?例如,

    class foo extends Component {
      constructor() {
        this.state = {
          one: true,
          two: false,
        }
      }
    
      getDerivedStateFromProps(props, state) {
        ...
        return {
          one: false,
        }
      }
    
      ...  
    }
    

    州政府是否会:

    { one: false }
    

    {
      one: false,
      two: false,
    }
    

    ?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Tholle    6 年前

    as it is stated in the documentation

    getDerivedStateFromProps

    class App extends React.Component {
      state = { one: 1 };
    
      static getDerivedStateFromProps() {
        return { two: 2 };
      }
    
      render() {
        return <div>{JSON.stringify(this.state)}</div>;
      }
    }
    
    ReactDOM.render(<App />, document.getElementById('root'));
    <script src="https://unpkg.com/react@16.4.1/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@16.4.1/umd/react-dom.production.min.js"></script>
    
    <div id="root"></div>