getDerivedStateFromProps prevState为null

时间:2019-02-05 14:11:28

标签: reactjs

enter image description heregetDerivedStateFromProps内部,prevState在初始加载时为空。 请在下面找到代码示例:

class extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            pathname: props.location.pathname,
            search: props.location.search,
        };
    }
    static getDerivedStateFromProps(nextProps, prevState) {
        // prevState is null
        const {
            location: { pathname, search },
        } = nextProps;
        if (
            pathname !== prevState.pathname ||
            search !== prevState.search
        ) {
            return {
                pathname,
                search,
            };
        }
        return null;
    }
    componentDidUpdate(prevProps, prevState) {
        if (
            prevState.pathname !== this.state.pathname ||
            prevState.search !== this.state.search
        ) {
            // Perform some operation here
        }
    }
    render() {
        return <SomeComponent {...this.props} />;
    }
};

getDerivedStateFromProps-> https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

1 个答案:

答案 0 :(得分:0)

这似乎不正确。参见下面的工作示例:

class Foo extends React.Component {
    constructor(props) {
      super(props)
      this.state = {
        bar: 1
      }
    }
    
    static getDerivedStateFromProps(props, state) {
      console.log("State", state)
      return null
    }
    
    render() {
      return <div>Hello</div>
    }
}

ReactDOM.render(<Foo />, document.querySelector("#root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />