reactjs - 使用 componentWillReceiveProps 更新状态
问题描述
我正在查看其他代码,该代码更新了反应生命周期中的对象状态:componentWillReceiveProps。我对 react 和 redux 还很陌生,但我认为你在 reducer 中进行了所有状态更新,而对其本地状态毫无用处。有人能告诉我他为什么在 componentWillReceiveProps 中这样做吗?谢谢
componentWillReceiveProps(nextProps) {
if(this.props.isEditingbook && !nextProps.isEditingbook) {
let book = this.props.index.bookDictionary[this.props.currentbook.id]
book.name = this.state.model.name.value
}
this.setState({ ...this.state, ...nextProps})
}
解决方案
好吧,首先,componentWillrecieveProps
它已被弃用,因为它可能会导致一些问题,看看这里。相反,React 文档指出您应该使用componentDidUpdate
安全使用的方法。
并回答您的问题,如果您查看了该人使用 redux 的代码,那么他使用了已弃用的方法,因为当您通过 将组件绑定到 redux goblal state (store) 时mapStateToProps
,它的属性将绑定到该组件道具。所以,换句话说,每当全局状态发生变化时,组件 props 也会发生变化,如果你想在你的组件逻辑中“跟踪”这些变化,你必须知道它的 props 什么时候会发生变化,这就是你使用componentWillRecieveProps
orcomponentDidUpdate
方法的原因.
以下是示例代码应该如何完成的componentDidUpdate
:
componentDidUpdate(prevProps) { //prevProps is the previous props of the component before being updated
//so, if this.props != prevProps it means that component props have been updated
if(this.props.isEditingbook && !prevProps.isEditingbook) {
let book = this.props.index.bookDictionary[this.props.currentbook.id]
book.name = this.state.model.name.value
}
this.setState({ ...this.state, ...prevProps})
}
推荐阅读
- .net - Entity Framework Core 2.0 选择多对多问题的查询
- linux - 如何通过 ssh 进入远程服务器、运行命令并留在服务器上
- sql - SQL Server,需要 SQL 查询协助
- mongodb - 动态子字段的 MongoDB 索引
- jboss7.x - 如何在 JBoss AS 7 中正确设置 MySQL 数据源?
- java - 二次方程 Java 类
- node.js - secretOrPrivateKey 必须有一个值
- sql - AUTOCOMMIT_DDL 是否适用于基于 ABAP 的系统,非 HANA 系统?
- swift - 传递带有重载的函数不会编译
- php - 将php sql行记录插入隐藏表单输入值字段