【发布时间】: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