简体   繁体   中英

redux reset state when changing pages

So i've implemented infinite scroll with redux. Everythings works its just that when I change pages then go back to the home page, it shows the posts i scrolled down to times two. I'm assumming the issue here is with the way i setup my redux. I've been scouring here and the only thing that sounded logical to me was to reset the state on component unmount. I've created it in my actions and added it to my useEffect and it still dont work. Is there a way when I leave my home page, it will reset so that when i go back to my home page it will fetch all posts again? Im stuck. Help please

HomePage

const [page, setPage] = useState(1);
const dispatch = useDispatch();
const { loading, posts, total } = useSelector((state) => state.posts);

useEffect(() => {
    dispatch(getPosts(page));

    return () => {
      dispatch(resetPosts());
    };
  }, [dispatch, page]);

Actions

export const getPosts = (page) => async (dispatch) => {
  try {
    const {
      data: { posts, totalPosts },
    } = await api.fetchPosts(page);

    dispatch({
      type: PC.FETCH_ALL_POSTS_SUCCESS,
      payload: { posts, totalPosts },
    });
  } catch (error) {
    dispatch({ type: PC.FETCH_ALL_POSTS_FAIL, payload: error.response });
  }
};
export const resetPosts = () => {
  return { type: PC.RESET_POSTS };
};

Reducers

export const postsReducer = (state = { posts: [] }, action) => {
  switch (action.type) {
    case PC.FETCH_ALL_POSTS_REQUEST:
      return { loading: true };
    case PC.FETCH_ALL_POSTS_SUCCESS:
      return {
        loading: false,
        posts: [...state.posts, ...action.payload.posts],
        total: action.payload.totalPosts,
      };
    case PC.FETCH_ALL_POSTS_FAIL:
      return { loading: false, error: action.payload };
    case PC.RESET_POSTS:
      return state;

It looks like you are storing your redux state incorrectly. Try edited your logic where you are using the spread operator. It should probably be

return {
        loading: false,
        posts: action.payload.posts,
        total: action.payload.totalPosts,
      }

This way you are actually updating your state and not making all of your state just one big posts array. I can see what you were trying to do, but that is only really needed if you are doing your return object like

return { ...state, posts: action.payload.data } 

and need to maintain other state variables alongside the posts.

A tool that could help you debug this better in the future is the redux chrome dev tools. https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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