首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用getDerivedStateFromProps状态到道具

使用getDerivedStateFromProps状态到道具
EN

Stack Overflow用户
提问于 2018-11-13 20:26:01
回答 1查看 580关注 0票数 1

因此,我试图制作一个从服务器请求数据的组件,并且我希望能够在提交数据之前更改它,之前我会这样做的。

代码语言:javascript
复制
componentWillReceiveProps(nextProps) {
    if (nextProps.dwelling) {
        this.state.dwelling = nextProps.dwelling;
    }
    if (!nextProps.saving && this.props.saving) {
        this.props.history.push('/users');
    }
}
}

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

但是,由于不推荐componentWillReceiveProps,所以我也试图对getDerivedStateFromProps做同样的事情:

代码语言:javascript
复制
static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.dwelling !== prevState.dwelling) {
        return {dwelling: nextProps.dwelling}
    }
    return null
}

问题是在每个呈现方法之后都调用了getDerivedStateFromProps,并且干扰了我的onChange处理程序,是否有任何替代componentWillReceiveProps的方法?我看到了一篇关于使用shouldComponentUpdate的帖子,但这似乎不是使用该方法的目的。

编辑: componentDidUpadte完成了以下工作:

代码语言:javascript
复制
componentDidUpdate(prevProps) {
    if (this.props.dwelling !== prevProps.dwelling){
        this.setState(() => ({dwelling: this.props.dwelling}));
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-13 20:29:41

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

不过,要回答你的问题..。你为什么不选择在componentDidUpdate中这样做呢?这可能比使用getDerivedStateFromProps更好。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53288967

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档