【发布时间】:2018-01-21 23:13:30
【问题描述】:
我正在 react-redux 中做一个应用程序,我想在页面刷新时保留我的 redux 商店,并认为不使用预定义的库,因此我将 redux 状态设置为本地状态并在 componentWillUnmount 中进行 api 调用在页面刷新时恢复 redux 状态。但它不能这样做。他们是否有任何方法可以实现这一点:
我的代码是:
componentWillMount(){
this.setState({
activeUser:this.props.activeUser
})
}
componentWillUnmount(){
this.props.loginUser(this.state.activeUser.user);
}
activeUser 是我的 redux 状态,this.props.loginUser() 进行 api 调用。我尝试使用事件处理程序:
componentDidMount(){
window.addEventListener('onbeforeunload', this.saveStore)
}
componentWillUnmount(){
window.removeEventListener('beforeunload', this.saveStore)
}
saveStore(){
this.props.loginUser(this.state.activeUser.user);
}
但它对我不起作用。
【问题讨论】:
-
我认为您不能在刷新时保留状态。您要么需要使用本地/会话存储来存储状态,要么将您的状态写入 json 文件并从那里恢复,并在刷新完成后恢复
-
您需要做的是将商店保存在 localStorage 中,并在您的页面再次打开时加载它。您可以在您的主应用程序中执行此操作