首页 > 解决方案 > 在卸载时保留反应组件状态

问题描述

在这里反应新手:我注意到组件状态在卸载时被清除。有没有办法防止它?是使用redux吗?

标签: reactjsreact-redux

解决方案


你有很多选择。您可以使用状态管理工具,如redux上下文 API等,也可以将回调传递给父组件并childComponentWillUnmount像这样触发它:

父组件.jsx:

childComponentWillUnmount = (data) => {
 console.log('my data', data);
}

render(){
  return <div>
    <Child componentUnmountCallback={this.childComponentWillUnmount()}/>
  <div>
}
<div>

子.jsx

...

componentWillUnmount() {
   this.props.childComponentWillUnmount(this.state);

}

...

推荐阅读