[英]Redux-thunk - dispatch is not a function
我在使用 redux-thunk 時遇到了麻煩。 它說 dispatch 不是我的動作創建者內部的函數,我嘗試安慰返回的參數,但沒有。
代碼如下:
行動
export function signUp(data) {
return dispatch => {
console.log(dispatch)
if (data.email === 'email@server.com') {
dispatch(signIn(data, () => {
if (data.type === '2') {
browserHistory.push('/settings/profile')
} else {
browserHistory.push('/')
}
}))
} else {
return {
type: ActionTypes.USER_SIGN_UP__ERROR
}
}
}
}`
mapActionsToProps
const mapActionsToProps = dispatch => ({
signUp (data) {
console.log(dispatch)
dispatch(userActions.signUp(data))
}
})
順便說一下,你可以看到我在 mapActionsToProps 中控制了 dispatch 函數,並且它按照預期返回:
function (action) {
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
return next(action);
}
Dispatch 不是函數,因為它不是從動作創建者傳遞的。
此外,你不應該在你的 mapActionsToProps 中調度任何動作。 你只需要綁定它們就可以被連接的組件訪問。
你的 mapActionsToProps
const mapActionsToProps = (dispatch) => {
return {
asyncAction: bindActionCreators(asyncAction, dispatch),
}
}
const Container = connect(mapStateToProps, mapActionsToProps)(Component);
異步操作
export const asyncAction = (email) => {
return (dispatch, getState) => {
const state = getState();
dispatch(StartAsync());
return fetch(`${apiUrl}/endpoint?email=${email}`, {
method: 'GET'
})
.then(response => response.json())
.then((result) => dispatch(finishedAsync(result)),
(error) => dispatch(failedAsync(error)))
.catch(e => {
console.log('error:', e);
});
};
};
然后,在你連接的組件中,你可以從 props 調度這個動作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.