编辑:已解决!请参阅below .
我希望我的 Blog
组件在每次浏览器请求其 URL(无论是通过链接还是刷新)时触发 fetchBlog
操作创建者。我想使用 React useEffect
Hook 以及 React-Redux useDispatch
和 useSelector
Hook 来完成此操作。但是,我的操作仅在点击页面链接时才会触发;即使阅读了几个解释(例如 the official docs ),我也不明白为什么。
这是代码:
// Everything duly imported, or else VSC would yell at me
export default function Blog() {
const dispatch = useDispatch();
// slug is set here with useSelector, this always works
useEffect(() => {
dispatch(fetchBlog(slug))
}, [slug, dispatch]);
const blog = useSelector((state) => state.blogs[0]);
// return renders the blog information from the blog constant
// since the action does not fire, blog is undefined because state.blogs is an empty array
}
我知道,刷新时,fetchBlog
不会触发,因为 Redux DevTools 以及我在那里放置了一个调试器
。 (后端日志不会显示传入的请求。) Action 创建者本身和 reducer 必须正在工作;如果不是,则通过链接访问时页面将无法正确加载。
编辑:我确定 useSelector
和 useDispatch
不是问题的根本原因,因为将代码更改为使用 connect
与 mapStateToProps
和 mapDispatchToProps
给出相同的结果。问题似乎出在 useEffect
上。
最佳答案
我认为问题是您正在将调用返回给调度。从 useEffect 返回的函数是清理函数,因此我认为这不会在安装或更新时运行 - 仅在卸载之前运行。试试这个:
export default function Blog() {
// ...
// Don't return from useEffect. Just call dispatch within the body.
useEffect(() => {
dispatch(fetchBlog(slug);
}, [slug, dispatch]);
// ...
}
https://reactjs.org/docs/hooks-reference.html#cleaning-up-an-effect
关于javascript - 使用 React 和 Redux Hooks,为什么我的操作没有触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59073134/