因此,我尝试将信息从登录表单发送到操作,然后在登录过程成功时将应用程序的状态userLogged属性设置为true。
renderForm() {
return (
<Form
onSubmit={(values) => {
// call the login function.
// if called with this.props.login, I get the error
// 'cannot read `type` of undefined'
login(values.email, values.password);
}}
validate={({ email, password }) => {
// validation rules
}}>
{({submitForm}) => {
return (
<form onSubmit={submitForm}>
// form fields
</form>
);
}}
</Form>
);
}
现在,在声明组件后,我有以下内容:
function mapDispatchToProps(dispatch) {
return bindActionCreators({ login }, dispatch);
}
function mapStateToProps(state) {
return { userLogged: state.userLogged.userLogged };
}
export default connect(mapStateToProps, mapDispatchToProps)(LoginComponent);
操作接收信息,调用API,但没有到达reducer,应用程序提供未定义的&#39; dispatch&#39;错误,即使已经导入了商店,中间件和bindActionCreators。
export function login(email, password) {
const request = axios({
headers: {
'content-type': 'application/json'
},
method: 'post',
url: `${ROOT_URL}login/login`,
params: {
email,
password
}
})
.then((data) => dispatch(dispatchLogin(data)));
}
function dispatchLogin(data) {
return {
type: 'USER_LOGIN',
payload: data
};
}
reducer应该检索操作的类型并操作编辑应用程序的状态。
export default function (state = {}, action) {
switch (action.type) {
case 'USER_LOGIN': {
console.log(action.payload.data);
state.userLogged = action.payload.data.status;
return { ...state }
}
default: return state;
}
}
答案 0 :(得分:3)
Redux操作默认是同步的,你必须使用像redux-thunk这样的中间件来进行异步操作:https://github.com/gaearon/redux-thunk
示例(未经测试):
export function login(email, password) {
return async (dispatch, getState) => {
let data = await axios({
headers: {
'content-type': 'application/json'
},
method: 'post',
url: `${ROOT_URL}login/login`,
params: {
email,
password
}
});
dispatch(dispatchLogin(data));
};
}