首页 > 解决方案 > 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)
    }
}

标签: reactjsreduxreact-redux

解决方案


尝试使用扩展运算符

import Toolbar from './Toolbar.Component';

export default connect<any, any, any>((store:any) => {
    return { ...store.toolbarComponent }  <-- Here
}, {})(Toolbar)

说明- 组件挂钩未检测到对象的更改store.toolbarComponent,传播运算符克隆store.toolbarComponent对象并传递克隆版本。


推荐阅读