Javascript 如何在 React.js 中刷新页面后保持状态?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28314368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to maintain state after a page refresh in React.js?
提问by DiverseAndRemote.com
Lets say I have code that sets state for a select box chosen on the previous page:
假设我有为上一页选择的选择框设置状态的代码:
this.setState({selectedOption: 5});
Is there any way to have this.state.selectedOptionpopulated with 5 after a page refresh?
有没有办法this.state.selectedOption在页面刷新后填充 5?
Are there callbacks that I can use to save this in localStorage and then do one large setStateor is there a standard way of doing something like this?
是否有回调可用于将其保存在 localStorage 中,然后执行一个大的回调,setState或者是否有执行此类操作的标准方法?
回答by DiverseAndRemote.com
So my solution was to also set localStoragewhen setting my state and then get the value from localStorageagain inside of the getInitialStatecallback like so:
所以我的解决方案是localStorage在设置状态时也设置,然后从回调localStorage内部再次获取值,getInitialState如下所示:
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-Patternbut it works unless there is a better solution.
我不确定这是否可以被视为反模式,但除非有更好的解决方案,否则它可以工作。
回答by juliangonzalez
You can "persist" the state using local storage as Omar Suggest, but it should be done once the state has been set. For that you need to pass a callback to the setStatefunction and you need to serialize and deserialize the objects put into local storage.
您可以像 Omar Suggest 一样使用本地存储“持久化”状态,但是一旦设置了状态就应该这样做。为此,您需要将回调传递给该setState函数,并且需要对放入本地存储的对象进行序列化和反序列化。
constructor(props) {
super(props);
this.state = {
allProjects: JSON.parse(localStorage.getItem('allProjects')) || []
}
}
addProject = (newProject) => {
...
this.setState({
allProjects: this.state.allProjects.concat(newProject)
},() => {
localStorage.setItem('allProjects', JSON.stringify(this.state.allProjects))
});
}
回答by Matt Holland
We have an application that allows the user to set "parameters" in the page. What we do is set those params on the URL, using React Router (in conjunction with History) and a library that URI-encodes JavaScript objects into a format that can be used as your query string.
我们有一个应用程序,允许用户在页面中设置“参数”。我们所做的是在 URL 上设置这些参数,使用 React Router(结合 History)和一个库,该库将 JavaScript 对象 URI 编码为可用作查询字符串的格式。
When the user selects an option, we can push the value of that onto the current route with:
当用户选择一个选项时,我们可以将其值推送到当前路由上:
history.push({pathname: 'path/', search: '?' + Qs.stringify(params)});
pathnamecan be the current path. In your case paramswould look something like:
pathname可以是当前路径。在你的情况下params看起来像:
{
selectedOption: 5
}
Then at the top level of the React tree, React Router will update the propsof that component with a prop of location.searchwhich is the encoded value we set earlier, so there will be something in componentWillReceivePropslike:
然后在 React 树的顶层,React Router 将props使用location.search我们之前设置的编码值的 prop更新该组件的,所以会有componentWillReceiveProps类似的东西:
params = Qs.parse(nextProps.location.search.substring(1));
this.setState({selectedOption: params.selectedOption});
Then that component and its children will re-render with the updated setting. As the information is on the URL it can be bookmarked (or emailed around - this was our use case) and a refresh will leave the app in the same state. This has been working really well for our application.
然后该组件及其子组件将使用更新的设置重新渲染。由于信息位于 URL 上,因此可以将其添加为书签(或通过电子邮件发送 - 这是我们的用例),刷新将使应用程序处于相同状态。这对我们的应用程序来说非常有效。
React Router: https://github.com/reactjs/react-router
反应路由器:https: //github.com/reactjs/react-router
History: https://github.com/ReactTraining/history
历史:https: //github.com/ReactTraining/history
The query string library: https://github.com/ljharb/qs
查询字符串库:https: //github.com/ljharb/qs
回答by mattwarren
I consider state to be for view only information and data that should persist beyond the view state is better stored as props. URL params are useful when you want to be able to link to a page or share the URL deep in to the app but otherwise clutter the address bar.
我认为状态仅用于查看信息,并且应该在视图状态之外持续存在的数据最好存储为道具。当您希望能够链接到一个页面或在应用程序的深处共享 URL 但否则地址栏会变得混乱时,URL 参数很有用。
Take a look at Redux-Persist (if you're using redux) https://github.com/rt2zz/redux-persist
看看 Redux-Persist(如果您使用的是 redux)https://github.com/rt2zz/redux-persist
回答by sMojtaba Mar
Load statefrom localStorage if exist:
如果存在,则从 localStorage加载状态:
constructor(props) {
super(props);
this.state = JSON.parse(localStorage.getItem('state'))
? JSON.parse(localStorage.getItem('state'))
: initialState
override this.setStateto automatically save stateafter each update :
覆盖this.setState以在每次更新后自动保存状态:
const orginial = this.setState;
this.setState = function() {
let arguments0 = arguments[0];
let arguments1 = () => (arguments[1], localStorage.setItem('state', JSON.stringify(this.state)));
orginial.bind(this)(arguments0, arguments1);
};
回答by Raj Gohel
Try to store value in local storage and at the time of page load get value from local storage. If you have some more values you should use redux for data storage.
尝试将值存储在本地存储中,并在页面加载时从本地存储中获取值。如果你有更多的值,你应该使用 redux 来存储数据。

