【问题标题】:State to props with getDerivedStateFromProps使用 getDerivedStateFromProps 状态到道具
【发布时间】:2018-11-13 20:26:01
【问题描述】:

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

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

注意:第二个if在保存成功后推送也很方便。

但由于 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}));
    }
}

【问题讨论】:

  • getDerivedStateFromProps 在每个渲染方法之后调用 是的 getDerivedStateFromProps 将在您更改状态或更改道具时调用。如果您想阻止在props 更改时呈现,请使用shouldComponentUpdate

标签: reactjs


【解决方案1】:

首先,在您的 componentWillReceiveProps 示例中,您不应该直接设置状态。相反,你应该打电话给this.setState

但是,要回答您的问题……您是否有理由不选择在componentDidUpdate 中执行此操作?这可能比使用getDerivedStateFromProps 更好。

【讨论】:

  • 注意:componentDidUpdate 将导致在 setState 调用上重新渲染,而 getDerivedStateFromProps 不会。
  • 正确,虽然作为一种静态方法,我认为getDerivedStateFromProps 不是一个很好的地方来做副作用,比如在 OP 的例子中推动历史。
  • 从不担心 componentDidUpdate!谢谢,顺便说一句,这是使用功能 setstate 的正确方法吗?我将解决方案添加到我的帖子中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-20
  • 2020-07-26
  • 1970-01-01
  • 2020-01-23
相关资源
最近更新 更多