如何访问 redux 中 mapDispatchToProps 中的全局状态?

How do I get access to the global state in mapDispatchToProps in redux?

我想分派一个操作来使用当前登录的用户更新我的应用程序的全局状态。当用户单击一个按钮时,将触发一个在 mapDispatchToProps 中注册的事件处理程序,然后我想调度一个操作 (article.updateAuthor(currentUser))。但是,在 mapDispatchToProps 中,我无权访问状态来获取当前用户,并且我不想随意将当前登录的用户传递给组件道具——只传递给上面的点击事件,然后会将用户数据传递给已调度的操作。

我知道我可以使用 redux thunk 发送一个动作,这让我可以访问状态。但是,由于没有进行 API 调用,这似乎相当笨拙。

有没有人运行遇到过这个问题?

您可以考虑导入您的商店并使用 store.getState(),这样您就可以访问您的 "global" 商店。

但请记住,不推荐使用这种方法,如果您使用 connect.

,您应该按照@markerikson 回答的建议使用 mergeProps

getState()

Returns the current state tree of your application. It is equal to the last value returned by the store's reducer. Source.

伪代码:

import store from 'store'
store.getState().yourReducer.user.current

你不能。 mapDispatch 故意不授予对状态的访问权限,因为您通常使用 mapDispatch 来创建绑定函数,并且基于状态这样做会不断导致这些函数在状态更改时重新创建。

如果您真的想要这样做,您可以使用 connect 的第三个参数,称为 mergeProps,但这通常应该只是用作最后的手段。

推荐的方法是:

  • 提取mapState中的相关数据,调用组件this.props.someFunction(this.props.someRelatedValue)
  • 使用 thunk 并访问其中的状态

总体而言,访问 thunk 中的状态是完全有效且受支持的功能。有些人担心这样做是否是个好主意,我在我的博客 post Idiomatic Redux: Thoughts on Thunks, Sagas, Abstraction, and Reusability.

中解决了这些问题

react-redux 提供的 connect 函数中,您可以使用四个可选参数:

  • mapStateToProps
  • mapDispatchToProps
  • mergeProps(这个给你想要的)
  • options

来自 mergeProps 的文档:

If specified, it is passed the result of mapStateToProps(), mapDispatchToProps(), and the parent props. The plain object you return from it will be passed as props to the wrapped component. You may specify this function to select a slice of the state based on props, or to bind action creators to a particular variable from props

因此,在您的情况下,您将使用 mapStateToProps 来访问您需要的全局状态的任何部分。结果将作为 stateProps 参数传递给 mergeProps

mergeProps中做你需要用这个状态做的事情,使用dispatchProps的结果(或者从中解构dispatch)和return你的对象需要在您要连接的组件中。

在mapDispatchToProps中访问不到state真是可笑

redux还有一个替代方案Dynadux,简单又解决了redux的繁琐

另外,ispatches 可以在没有 Thunk 的情况下从 reducer 中触发。