如何在页面刷新时保留状态值

问题描述 投票:1回答:1

我使用localstorage.setItem()来存储将在页面刷新时工作的状态,但localstorage在我的情况下不起作用。我的状态在页面刷新时并不持久。 我需要全局保存用户ID,这也需要在整个项目中保留页面刷新。请帮我解决这个问题。任何帮助,将不胜感激。

        function setUserId(user_id = '', action) {
          switch (action.type) {
            case 'ADD_ID':
            return user_id = action.id;
            default:
            return user_id = action.id;
          }
        }
        const loadState = () => {
          try {
            const serializedState = localStorage.getItem("state");

            if (serializedState === null) {
              return undefined;
            }

            return JSON.parse(serializedState);

          } catch (err) {
            return undefined;
          }
        };

        const store = createStore(setUserId,loadState());

        function saveState(state) {
                try {
                    let serializedState = JSON.stringify(state);
                    localStorage.setItem("state",serializedState);
                }
                catch (err) {
                }
            }

        handleClick(event) {
      let that = this;
      axios.post(apiBaseUrl, payload)
      .then(function (response) {
        console.log(response);
        if(response.status == 200){
          console.log("Login successfull");
          store.dispatch({
            type: 'ADD_ID',
            id: response.data.id
          })
          store.subscribe(() => {
            //this is just a function that saves state to localStorage
            saveState(store.getState());
          });

          that.setState({
            isLoggedIn: true,
            access_token: response.data.access_token,
            user_id: response.data.id
          })

        }

        else if(response.status == 204){
          console.log("Username password do not match");
          alert("username password do not match")
        }
        else{
          console.log("Username does not exists");
          alert("Username does not exist");
        }
      })
      .catch(function (error) {
        console.log(error);
      });
    }
reactjs redux
1个回答
0
投票

从你的try/catch删除saveState()。如果要在子组件树中的任何位置捕获JavaScript错误。并尝试在statesaveState()中进行控制。

© www.soinside.com 2019 - 2024. All rights reserved.