如何在 React.js 中刷新页面后保持状态? [英] How to maintain state after a page refresh in React.js?

查看:190
本文介绍了如何在 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 然后从 localStorage 获取值再次在 getInitialState 回调中,如下所示:

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 } );
}

我不确定这是否可以被视为 Anti-Pattern 但除非有更好的解决方案,否则它可以工作.

I'm not sure if this can be considered an Anti-Pattern but it works unless there is a better solution.

这篇关于如何在 React.js 中刷新页面后保持状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆