[英]Redux-thunk "dispatch is not a function"
我已经通过以下方式配置了 redux-thunk
import {BrowserRouter} from "react-router-dom";
import {createStore, applyMiddleware, compose} from "redux";
import Provider from "react-redux/es/components/Provider";
import braintrainer from "./store/reducers/braintrainer";
import thunk from 'redux-thunk';
const store = createStore(
braintrainer,
applyMiddleware(thunk),
);
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<BrainTrainer/>
</BrowserRouter>
</Provider>
, document.getElementById('root'));
然后在我的一个组件中,我映射函数 onLoginClicked 以分派 startLogin 操作
const mapDispatchToProps = dispatch => ({
onDifficultySelected: difficulty => dispatch({ difficulty, type: 'SET_DIFFICULTY' }),
onLoginClicked : (username,password) => dispatch(() => startLogin(username,password))
});
export default withRouter(connect(null, mapDispatchToProps)(BrainTrainer));
我将 onLoginClicked 函数向下传递到我的登录组件,并在单击登录按钮时调用它
<button type='button' className='login-btn' onClick={onLoginClicked(passWord,userName)}>
{isLogin ? 'Login' : 'Sign up'}
</button>
我的 startLogin 动作创建者看起来像这样
import axios from 'axios';
const baseUrl = 'http://localhost:5000';
export const login = (token) => ({
type: 'LOGIN',
token
});
export const startLogin = (password,username) => {
return dispatch => {
axios.post(baseUrl+'/api/auth/login',{
username,
password
}).then((data) => dispatch(login(data.data.token)))
}
};
然而,当我调用 onLoginClicked 函数时,我在 startLogin 操作创建者中遇到了这个错误。
Unhandled Rejection (TypeError): dispatch is not a function
谁能告诉我哪里出错了?
错误图片
在dispatch(fn)
中, fn
需要是一个“thunk”函数——接受dispatch
本身作为第一个参数。 不是匿名函数:
dispatch(() => startLogin(username,password))
但是startLogin
的返回值:
dispatch(startLogin(username,password))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.