我正在使用redux connect和redux-thunk中间件和容器.
目前,当用户执行操作时,例如,单击一个按钮,我需要调度该动作(同步),该动作将调度其他几个动作(异步).
我知道在reducer中调度动作是一种反模式.
我想知道这个代码适合什么地方.
目前我不确定它是否应该留在:
Mμ.*_*Mμ. 27
根据文档推荐的方法是在动作创建者中,如下所示:
function actionCreator(payload) {
return dispatch => {
dispatch(action1(payload))
dispatch(action2(payload))
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可能想要将动作创建者附加为prop并使用mapDispatchToProps类似于此处提到的示例将其传递给容器.所以它看起来像这样:
const mapDispatchToProps = dispatch => ({
action1: some_payload => dispatch(action1(some_payload))
action2: some_payload => dispatch(action2(some_payload))
})
// your component
export default connect(mapStateToProps, mapDispatchToProps)(YourApp)
Run Code Online (Sandbox Code Playgroud)
Gib*_*boK 18
正如其他指出的那样,The action creator是调度多个行动的正确位置.
下面是一个如何action1在你的手中发送其他动作的例子action creator.
const action1 = id => {
return dispatch => {
dispatch(action2(id))
dispatch(action3(id))
}
}
Run Code Online (Sandbox Code Playgroud)
操作创建者是分派多个操作的正确位置。虽然像下面的代码可以工作:
function actionCreator(payload) {
return dispatch => {
dispatch(action1(payload))
dispatch(action2(payload))
}
}
Run Code Online (Sandbox Code Playgroud)
我强烈建议redux-thunk基于动作的创建者始终返回已解决的Promise,以便此类动作创建者可以成为另一个异步调用的一部分。因此,对上述内容的最简单更新是:
function actionCreator(payload) {
return dispatch => {
dispatch(action1(payload));
dispatch(action2(payload));
return Promise.resolve();
}
}
Run Code Online (Sandbox Code Playgroud)
actionCreator(payload).then(doAnotherAction(anotherPayload))
如果我们需要保持调用顺序,则可以使用:或以下内容调度到上述
内容:
actionCreator(payload).then(() => doAnotherAction(anotherPayload))
如果您希望动作创建者“适应未来”,以便它可以处理调用异步和同步动作创建者,则可以将其编写为:
function actionCreator(payload) {
return dispatch =>
Promise.resolve(dispatch(action1(payload))).then(
() => dispatch(action2(payload)));
}
Run Code Online (Sandbox Code Playgroud)
而且,如果您喜欢ES6箭头符号,则可以将以上定义为:
const actionCreator = payload => dispatch =>
Promise.resolve(dispatch(action1(payload))).then(
() => dispatch(action2(payload)));
Run Code Online (Sandbox Code Playgroud)