【问题标题】:Getting error on page refresh when trying to maintain the state after page refresh页面刷新后尝试保持状态时出现页面刷新错误
【发布时间】:2021-11-03 14:39:10
【问题描述】:

我正在尝试在 React 中保持页面刷新后的状态:

这是我的代码:

class App extends React.Component{
    constructor(props){
        super(props);
        this.state = JSON.parse(localStorage.getItem("app_state")) ? JSON.parse(localStorage.getItem("app_state")) : {
            account: {
                email: "",
                password: ""
            },
            token: "",
            authenticated: false
        };

    }


    componentDidUpdate(prevProps, prevState){
        if(this.state.token !== prevState.token){ //set a new state if token changes
            localStorage.setItem("app_state", this.state);
        }
    }
    
    
    
    
    logInStatus = () =>{

        if(!this.state.authenticated) {
            return (
                <form onSubmit={this.handleSubmit}>
                    
                    <label>Email Address</label>
                    <input type="text" value={this.state.passAccount.email} onChange={this.handleChange} name="email"/>                
                
                    <label>Password</label>
                    <input type="password" value={this.state.passAccount.password} onChange={this.handleChange} name="password" />
     
                    
                    <br/>                    
                    <Button type="submit" onClick={() => {
                        this.someFunction(String(this.state.passAccount.email));
                    }}>
                        Sign In</Button>
                </Form>
            );
        }else{
            return(<Redirect to="/some/endpoint" />);
        }
    }
    
    
    
}

export default App;

这是我正在做的以防止页面刷新时丢失状态:

在 componentDidUpdate 方法中,我正在检查令牌,如果不是 fount/与状态令牌不同,我将其保存在本地存储中。

在构造函数的状态中,我从本地存储中获取状态。

但是,我在页面刷新时收到以下错误:

这是本地存储的屏幕截图:

我的代码有什么问题,需要修复什么?

【问题讨论】:

    标签: javascript reactjs react-router react-hooks local-storage


    【解决方案1】:

    你不需要像那样从localStorageJSON.parse你的对象

    所以改为:

    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = localStorage.getItem("app_state") ?? {
          account: {
            email: "",
            password: ""
          },
          token: "",
          auth: false
        };
      }
    
      componentDidUpdate(prevProps, prevState) {
        if (this.state.token !== prevState.token) { // Set a new state if token change
          localStorage.setItem("app_state", this.state);
        }
      }
    ...the rest of your component
    

    在尝试新代码之前不要忘记清除当前存储空间

    【讨论】:

      猜你喜欢
      • 2019-05-19
      • 2020-08-14
      • 1970-01-01
      • 2021-04-24
      • 2018-07-25
      • 2021-02-12
      • 2023-02-26
      • 1970-01-01
      • 2013-01-25
      相关资源
      最近更新 更多