如何在React.js中刷新页面后维护状态? [英] How to maintain state after a page refresh in React.js?
问题描述
假设我有代码为上一页选择的选择框设置状态:
Lets say I have code that sets state for a select box chosen on the previous page:
this.setState({selectedOption: 5});
有没有办法让 this.state.selectedOption
在页面刷新后填充5?
Is there any way to have this.state.selectedOption
populated with 5 after a page refresh?
我是否可以使用回调来将其保存在localStorage中,然后执行一个大的 setState
或者有没有一种标准的方式来做这样的事情?
Are there callbacks that I can use to save this in localStorage and then do one large setState
or is there a standard way of doing something like this?
推荐答案
所以我的解决方案也是设置我的状态时设置 localStorage
然后在 getInitialState内再次从
回调如此: localStorage
获取值
So my solution was to also set localStorage
when setting my state and then get the value from localStorage
again inside of the getInitialState
callback like so:
getInitialState: function() {
var selectedOption = localStorage.getItem( 'SelectedOption' ) || 1;
return {
selectedOption: selectedOption
};
},
setSelectedOption: function( option ) {
localStorage.setItem( 'SelectedOption', option );
this.setState( { selectedOption: option } );
}
我不确定这是否可以被视为反模式但它有效但除非有更好的解决方案。
I'm not sure if this can be considered an Anti-Pattern but it works unless there is a better solution.
这篇关于如何在React.js中刷新页面后维护状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!