reactjs - React 生命周期钩子不适用于 redux 状态更新
问题描述
我正在使用 react with typescript 和 react-redux 包。
确实按照文档配置组件 - https://react-redux.js.org/introduction/quick-start
console.log 正在处理连接功能,但组件生命周期不起作用。
容器.ts
import Toolbar from './Toolbar.Component';
export default connect<any, any, any>((store:any) => {
console.log('++++++++++++++++++++',store.toolbarComponent);
return store.toolbarComponent
}, {})(Toolbar)```
组件.ts
export default class ToolbarComponent extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
activeProperty: '',
toolbarList: this.props.toolbarList
};
console.log('--- comp init ---', this.state);
this.dispatchData = this.dispatchData.bind(this);
}
UNSAFE_componentWillUpdate(){
console.log('-----', this.props.toolbarList, this.state.toolbarList)
}
componentWillUpdate(){
console.log('-----', this.props.toolbarList, this.state.toolbarList)
}
componentWillReceiveProps(){
console.log('-----', this.props.toolbarList, this.state.toolbarList)
}
componentDidUpdate(){
console.log('-----', this.props.toolbarList, this.state.toolbarList)
}
}
解决方案
尝试使用扩展运算符
import Toolbar from './Toolbar.Component';
export default connect<any, any, any>((store:any) => {
return { ...store.toolbarComponent } <-- Here
}, {})(Toolbar)
说明- 组件挂钩未检测到对象的更改store.toolbarComponent
,传播运算符克隆store.toolbarComponent
对象并传递克隆版本。
推荐阅读
- swift - 从非父视图控制器分配委托
- reactjs - 滚动时反应导航切换标签栏
- piranha-cms - 获取/设置块上的列表字段
- unity3d - 尝试启动 Unity / Unreal Engine 时收到错误 (API-MS-WIN-CRT-MATH)
- syntax - 在复杂条件下避免过多的括号
- cmake - CMake:所有子目录的 source_group
- elasticsearch - Windows 中无法识别 Elastic Search curl 命令
- c# - 解析作为 exe C# 的进程启动信息参数提供的 json 字符串
- bootstrap-4 - 打开模态时背景图像跳转
- python - 在抓取网站时,空值被解析为“N/A”字符串