【问题标题】:Clear redux state when page transition页面转换时清除 redux 状态
【发布时间】:2021-04-13 21:37:48
【问题描述】:

我做了一个博客并将单页状态存储到redux状态(singlePost)。当我转到特定的帖子页面时,将 singlePost 设置为帖子值。但是当我回到我的主页点击下一篇文章时,下一篇文章页面显示之前的值并立即转向新的值。

如果用户按下浏览器的返回按钮,我会尝试发送重置功能,但它似乎不起作用。有人可以指导我如何改进这一点吗?谢谢!

singlePostReducer.js

export const singlePostReducer = createSlice({
  name: "singlePost",
  initialState: {
    isLoadingPost: false,
    singlePost: "",
    newPostResponse: null,
  },
  reducers: {
    setIsLoadingPost: (state, action) => {
      state.isLoadingPost = action.payload.isLoading;
    },
    setSinglePost: (state, action) => {
      state.singlePost = action.payload;
    },
    setNewPostResponse: (state, action) => {
      state.newPostResponse = action.payload;
    },
    resetSinglePost: (state) => {
      state.singlePost = "";
    },
  },
});

SinglePost.js

 export default function PostPage() {
      const { id } = useParams();
      const singlePost = useSelector((store) => store.singlePost.singlePost);
      const { body, title, createdAt } = singlePost;
      const dispatch = useDispatch();
      const history = useHistory();

      //Does 
      if (history.goBack() || window.onpopstate) {
          dispatch(reset());
        }

      useEffect(() => {
        dispatch(getSinglePost(id));
        
      }, [id, dispatch]);
    
      return (
        <PostPageContainer>
          <h1>{title}</h1>
          <h4>{new Date(createdAt).toLocaleString()}</h4>
          <PostContent>{body}</PostContent>
        </PostPageContainer>
      );
    }

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    问题

    //Does
    if (history.goBack() || window.onpopstate) {
      dispatch(reset());
    }
    

    问题在于,正如所写,history.goBack() 总是会立即被调用。我不确定返回值是什么,但这与您无关。 window.onpopstate 需要分配一个回调才能工作,但这也不是你想要的,分配一个会覆盖全局值,根本不建议这样做。

    解决方案

    当组件卸载时,您可以从效果清理函数中调度您的休息操作。

    export default function PostPage() {
      const { id } = useParams();
      const singlePost = useSelector((store) => store.singlePost.singlePost);
      const { body, title, createdAt } = singlePost;
      const dispatch = useDispatch();
      const history = useHistory();
    
      useEffect(() => {
        dispatch(getSinglePost(id));
      }, [id, dispatch]);
    
      useEffect(() => {
        return () => dispatch(reset()); // <-- reset when unmounting
      }, []);
    
      return (
        <PostPageContainer>
          <h1>{title}</h1>
          <h4>{new Date(createdAt).toLocaleString()}</h4>
          <PostContent>{body}</PostContent>
        </PostPageContainer>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      • 2021-01-12
      • 1970-01-01
      • 2021-05-17
      相关资源
      最近更新 更多