【发布时间】:2018-05-26 14:37:22
【问题描述】:
我正处于了解 redux 状态管理的学习阶段,并且仍在尝试与令人眼花缭乱的样板代码和中间件丛林进行谈判,其中大部分我都相信是“良药”。所以我希望你能容忍我这个可能很初级的问题。
我知道redux-thunk 允许动作创建者异步进行并在随后的时间分派常规动作。例如,我可以在 actions.js 中定义一个 thunk 动作创建者:
export function startTracking() {
return (dispatch => {
someAsyncFunction().then(result => dispatch({
type: types.SET_TRACKING,
location: result
}))
})
}
然后像这样从 React 组件中调用它:
onPress={() => this.props.dispatch(actions.startTracking())}
我的问题是,与简单地从异步回调内部分派操作相比,上述代码有什么优势?
import { store } from '../setupRedux'
...
export function startTracking() {
someAsyncFunction().then(result => {
store.dispatch({
type: types.SET_TRACKING,
location: result
})
})
}
我会在我的组件中调用它
onPress={() => actions.startTracking()}
甚至
onPress={actions.startTracking}
像我在第二个示例中所做的那样,通过导入直接访问store 有什么问题吗?
【问题讨论】:
-
查看 redux creator stackoverflow.com/questions/35411423/…的这个答案
标签: reactjs react-native redux react-redux redux-thunk