javascript - 使用 React 和 Redux Hooks,为什么我的操作没有触发?

标签 javascript reactjs react-redux react-hooks

编辑:已解决!请参阅below .

我希望我的 Blog 组件在每次浏览器请求其 URL(无论是通过链接还是刷新)时触发 fetchBlog 操作创建者。我想使用 React useEffect Hook 以及 React-Redux useDispatchuseSelector 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 必须正在工作;如果不是,则通过链接访问时页面将无法正确加载。

编辑:我确定 useSelectoruseDispatch 不是问题的根本原因,因为将代码更改为使用 connectmapStateToPropsmapDispatchToProps 给出相同的结果。问题似乎出在 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/

相关文章:

mysql - 在状态中存储大量数据?

javascript - 在 jQuery 中发送给 .always 的参数是什么?

reactjs - 如何在不同的 URL 路由之间保存 redux 状态?

javascript - 正则表达式允许 < 和 >

javascript - react 路由器使用参数返回空对象

reactjs - 从react-router-redux获取当前位置

reactjs - 可见性组件 Prop 未触发 - 语义 UI React

reactjs - 如何使用 redux 和 react-native 打开模式

javascript - 管道 RxJS 可观察到现有主题

javascript - 使用图像而不是实际的 radio 输入有什么好处