使用本地存储持久化状态时状态字段未定义

state field undefined upon using local storage to persist state

这是我的代码,我使用的是 React: 我正在使用本地存储,以便即使在页面刷新后也能保持状态并保持在同一页面上。

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

    }






    notLoggedInhomePage = () =>{

        if(!this.state.authenticated) {
            return (
                <form onSubmit={this.handleSubmit}>
                    <br/>
                    
                        <label>Email Address</label>
                        <input type="text" value={this.state.account.email} onChange={this.handleChange} name="email"/>
                        
                        <label>Password</label>
                        <input type="password" value={this.state.account.password} onChange={this.handleChange} name="password" />

                    <div>
                        {this.state.errorMessage}</div>
                    <br/>
                    <Button type="submit"  onClick={() => {
                        this.someFunction(String(this.state.account.email));
                    }}>Sign In</Button>
                </form>
            );
        }else{
            return(<Redirect to="/items/somelink" />);
        }
    }


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


export default App;

这是我遇到的错误:

说的是email is undefined,是什么原因出现这样的错误信息,why/how是email undefined,虽然在状态下定义为空字符串

以上问题的可能修复方法是什么?

Using setItem inserts a DOMstring value into local storage, getItem returns said DOM string (MDN),当我运行你的代码片段 returns “[object Object]”,您可以使用

来解决这个问题
localStorage.setItem("app_state", JSON.stringify(this.state));

然后检索数据为:

this.state = localStorage.getItem("app_state") ? JSON.parse(localStorage.getItem("app_state")) : {
            account: {
                email: "",
                password: ""
            },
            errorMessage: "",
            token: "",
            authenticated: false
        };

本地存储只会return字符串。不是对象或数组。 您需要在将其分配给状态之前对其进行解析 JSON.parse(localStorage.getItem(app_state))

let appState = localStorage.getItem(app_state)
if(appState) {
  appState = JSON.parse(appState)
}

在你的代码中

state = getState()

const getState =() => {
  let appState = localStorage.getItem(app_state)
  if(appState) {
     return JSON.parse(appState)
  } else {
    return {
            account: {
                email: "",
                password: ""
            },
            errorMessage: "",
            token: "",
            authenticated: false
        };
  }
}