繁体   English   中英

redux的动作如何能够访问dispatch和getState?

[英]How does react redux's actions have access to dispatch and getState?

react redux docs的reddit示例中,即使从未导入actions.js,它们如何也可以访问dispatch和getState函数? 我认为您必须在使用的每个文件中导入每种方法。

该代码使用thunk中间件 ,请阅读异步操作部分以了解更多信息。

它无权从外部库访问功能。

fetchPostsIfNeeded ,这些是本地定义的函数参数。 只要您重命名了调用参数的其余代码,就可以将它们重命名为任意名称。 例如

export function fetchPostsIfNeeded(subreddit) {
  return (fireAction, findState) => {
    if (shouldFetchPosts(findState(), subreddit)) {
      return fireAction(fetchPosts(subreddit))
    }
  }
} 

等同于

export function fetchPostsIfNeeded(subreddit) {
  return (dispatch, getState) => {
    if (shouldFetchPosts(getState(), subreddit)) {
      return dispatch(fetchPosts(subreddit))
    }
  }
}

但是,命名对于文档来说是用户友好的,因为fetchPostsIfNeeded希望能够通过redux管道调度内部动作创建者fetchPosts()

在这种情况下,实际商店的调度功能很可能是通过props注入的依赖项,您可以考虑将其传递给匿名函数(作为参数),将其作为动作创建者自身内部模式的延续。

有关Dan Abramov 在egghead.io上的免费课程的应用程序,有很多可靠的视频可以很好地使商店通过。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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