代码之家  ›  专栏  ›  技术社区  ›  Nicolas Albarracin

使用getDerivedStateFromProps将状态转换为道具

  •  1
  • Nicolas Albarracin  · 技术社区  · 6 年前

    componentWillReceiveProps(nextProps) {
        if (nextProps.dwelling) {
            this.state.dwelling = nextProps.dwelling;
        }
        if (!nextProps.saving && this.props.saving) {
            this.props.history.push('/users');
        }
    }
    }
    

    注意:第二个if在成功保存后也非常有用。

    static getDerivedStateFromProps(nextProps, prevState) {
        if (nextProps.dwelling !== prevState.dwelling) {
            return {dwelling: nextProps.dwelling}
        }
        return null
    }
    

    编辑: 组件didupadte完成了任务:

    componentDidUpdate(prevProps) {
        if (this.props.dwelling !== prevProps.dwelling){
            this.setState(() => ({dwelling: this.props.dwelling}));
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Danny Delott    6 年前

    this.setState .

    componentDidUpdate ? 这可能比使用 getDerivedStateFromProps .