我已经通过以下方式配置了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
谁能告诉我我哪里出问题了?
错误图片
答案 0 :(得分:2)
在dispatch(fn)
中,fn
必须是一个“ thunk”函数-接受dispatch
本身作为第一个参数。不是匿名函数:
dispatch(() => startLogin(username,password))
但是startLogin
的返回值:
dispatch(startLogin(username,password))