我能看懂下面的示例代码:
const mapStateToProps = state => {
return {
todo: state.todos[0]
}
}
const mapDispatchToProps = dispatch => {
return {
destroyTodo: () =>
dispatch({
type: 'DESTROY_TODO'
})
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(TodoItem)
当在组件中时,我可以调用 this.props.destroyTodo()
以便它在函数内执行 dispatch(...)
。
这是根据手册(如果它是一个函数):
mapDispatchToProps: this parameter can either be a function, or an object.
If it’s a function, it will be called once on component creation. It will receive dispatch as an argument, and should return an object full of functions that use dispatch to dispatch actions.
If it’s an object full of action creators, each action creator will be turned into a prop function that automatically dispatches its action when called. Note: We recommend using this “object shorthand” form.
但我很难理解这个有效链式箭头函数(另一层函数)的现有代码:
export const createBillingRun = id => dispatch => {
$.ajax({
type: 'POST',
url: `/api/billing/billingtypes/${id}/createrun/`,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
}).done(() => dispatch(pollBillingRuns(id)));
};
我这里已经转成传统语法了:
export const createBillingRun = function(id) {
return function(dispatch){
$.ajax({
type: 'POST',
url: `/api/billing/billingtypes/${id}/createrun/`,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
}).done(() => dispatch(pollBillingRuns(id)));
}
}
这个函数然后映射到 redux connect
:
export default connect(
{...},
{
createBillingRun
},
)(ThePage);
从上面的代码来看,createBillingRun
返回了一个额外的函数层,所以如果我执行 createBillingRun(123)
,它会返回一个接受 dispatch 的函数
作为参数,这与传递到 connect
的第一个示例类似。那么谁在执行内部函数呢?
有人可以帮我理解为什么链式箭头函数会起作用吗?
最佳答案
这仅在您安装了 Redux Thunk 时有效。它是一个中间件,可以查看您何时返回函数、传递该函数调度并调用它。
https://github.com/reduxjs/redux-thunk
function createThunkMiddleware(extraArgument) {
return ({ dispatch, getState }) => next => action => {
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
return next(action);
};
}
const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;
export default thunk;
关于javascript - 具有链式箭头功能的 redux mapDispatchToProps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52654512/