Why getDerivedStateFromProps is called after setState?

后端 未结 5 1610
别那么骄傲
别那么骄傲 2021-02-06 23:02

React introduced new static method getDerivedStateFromProps(props, state) which is called before every render method, but why? Calling it after prop change makes se

5条回答
  •  死守一世寂寞
    2021-02-06 23:48

    I did something like this

    constructor(props) {
        super(props);
        this.state = {
            expanded: props.expanded,
            ownUpdate: false
        }
    }
    
    static getDerivedStateFromProps(props, state) {
        if (state.ownUpdate) {
            return {
                expanded: state.expanded,
                ownUpdate: false
            };
        } else if (props.expanded !== state.expanded) {
            return {
                expanded: props.expanded
            };
        }
        return null;
    }
    
    toggle() {
        this.props.onAftePress(this.state.expanded, this.props.index);
        this.setState({
            expanded: !this.state.expanded,
            ownUpdate: true
        })
    }
    

提交回复
热议问题