首页 > 解决方案 > 使用 getDerivedStateFromProps 状态到道具

问题描述

所以我试图制作一个从服务器请求数据的组件,我希望能够在我将它提交到其他地方之前更改它,以前我会这样做

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

注意:第二个if也非常好用,保存成功后push。

但由于 componentWillReceiveProps 已被弃用,我试图对 getDerivedStateFromProps 做同样的事情:

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

问题是在每个渲染方法之后都会调用 getDerivedStateFromProps 并且弄乱了我的 onChange 处理程序,是否可以替代 componentWillReceiveProps?我看到了一篇关于使用 shouldComponentUpdate 的帖子,但似乎这不是使用该方法的预期方式。

编辑:componentDidUpadte 完成了这项工作:

componentDidUpdate(prevProps) {
    if (this.props.dwelling !== prevProps.dwelling){
        this.setState(() => ({dwelling: this.props.dwelling}));
    }
}

标签: reactjs

解决方案


首先,在您的 componentWillReceiveProps 示例中,您不应该直接设置状态。相反,您应该调用this.setState.

但是,要回答您的问题……您是否有理由不选择这样做componentDidUpdate?这可能比使用getDerivedStateFromProps.


推荐阅读