简体   繁体   English

在 React/Redux 中刷新页面时丢失本地存储

[英]Losing Local Storage on Page Refresh in React/Redux

I'm using React and Redux and storing data in a loggedUser variable upon user login.我正在使用 React 和 Redux,并在用户登录时将数据存储在 loggingUser 变量中。

my login reducer looks like this:我的登录减速器看起来像这样:

const loginReducer = (state = null, action) => {
  switch (action.type) {
    case "SET_USER":
      if (action.data) userService.setToken(action.data.token);
      return action.data;
    default:
      return state;
  }
};

export const fetchUser = () => {
  return dispatch => {
    const userStr = window.localStorage.getItem("loggedVintageUser");
    const user = JSON.parse(userStr);
    if (user) {
      dispatch({ type: "SET_USER", data: user });
    }
  };
};

export const setUser = data => {
  return dispatch => {
    dispatch({ type: "SET_USER", data });
  };
};

export const login = data => {
  return async dispatch => {
    const user = await loginService.login({
      username: data.username,
      password: data.password
    });
    window.localStorage.setItem("loggedVintageUser", JSON.stringify(user));
    dispatch({ type: "SET_USER", data: user });
  };
};

In my core App component i'm dispatching the fetchUser and setUser creators在我的核心 App 组件中,我正在调度 fetchUser 和 setUser 创建者

  useEffect(() => {
    fetchUser();
  }, [props.fetchUser]);

  useEffect(() => {
    const loggedUserJSON = window.localStorage.getItem("loggedVintageUser");
    if (loggedUserJSON) {
      const user = JSON.parse(loggedUserJSON);
      props.setUser(user);
      userService.setToken(user.token);
    }
  }, []);

I'm displaying a list of favorite items for a user and when i go to refresh the page, i'm getting the following error:我正在显示用户最喜欢的项目列表,当我刷新页面时,出现以下错误:

TypeError: Cannot read property 'favorites' of null

Here is relevant code for my Favorites component.这是我的收藏夹组件的相关代码。 The error is triggered on the loggedUser.favorites data.该错误是在 loggingUser.favorites 数据上触发的。 I can see when visiting the favorites page, the loggedUser field is there and data displays fine but on refresh the loggedUser variable turns to null.我可以在访问收藏夹页面时看到,loggedUser 字段在那里,数据显示正常,但在刷新后,loggedUser 变量变为 null。

const searchCards = ({ loggedUser, search }) => {
  const favorites = loggedUser.favorites;
  console.log("FAVORITES", favorites);
  return search
    ? favorites.filter(a =>
        a.title
          .toString()
          .toLowerCase()
          .includes(search.toLowerCase())
      )
    : favorites;
};

const Cards = props => {
  useEffect(() => {
    setData(props.cardsToShow);
  }, [props]);

const [filteredData, setData] = useState(props.cardsToShow);

const mapStateToProps = state => {
  return {
    baseball: state.baseball,
    loggedUser: state.loggedUser,
    page: state.page,
    entries: state.entries,
    query: state.query,
    pageOutput: state.pageOutput,
    search: state.search,
    cardsToShow: searchCards(state)
  };
};

const mapDispatchToProps = {
  searchChange,
  fetchData,
  updateUser
};

I tried to add this before i render the data, but it's not working我试图在渲染数据之前添加它,但它不起作用

if (!props.loggedUser) return null;

How can i retain that state if a user is refreshing the page.如果用户正在刷新页面,我如何保持该状态。 The odd part is that on my home page where i have a similar sort of display a refresh isn't causing the same problems.奇怪的是,在我的主页上,我有类似的显示方式,刷新并没有导致相同的问题。

check once loggedUser is exist in state or not.检查一次loggedUser是否存在状态。 Print state using console.log(state).使用 console.log(state) 打印状态。 you may also open inspect tool and go to application tab and click on local storage, you will get localStorage data.您也可以打开检查工具并转到应用程序选项卡并单击本地存储,您将获得本地存储数据。

Well, i figured this out and got some help from this post here.好吧,我想通了这一点,并从这篇文章中得到了一些帮助。 Redux store changes when reload page 重新加载页面时 Redux 存储更改

My loggedUser state was disappearing after reload, so i just loaded the inital state for loggedUser pulling the data from the local storage:我的loggedUser状态在重新加载后消失了,所以我只是加载了loggedUser从本地存储中提取数据的初始状态:

function initState() {
  return {
    token: localStorage.token,
    firstName: localStorage.firstName,
    id: localStorage.id,
    favorites: localStorage.favorites,
    username: localStorage.username
  };
}

const loginReducer = (state = initState(), action) => {
  switch (action.type) {
    case "SET_USER":
      if (action.data) userService.setToken(action.data.token);
      return action.data;
    default:
      return state;
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM