我有这个Redux Thunk动作创建者:
const addAlert = (pos, msg) => ({
type: 'ADD_ALERT',
pos,
msg
})
// Login Email Field
export const emailField = (email) => {
return dispatch => {
// Update Input
dispatch(updateInput('field1', email));
//Email validator
if (email === '') {
dispatch(addAlert('field1', 'This field is empty'));
return;
}
// If all validators pass clear the alert
dispatch(deleteAlert('field1'))
};
}
我想将Email Validator部分移动到它自己的函数中,然后在该代码所在的相同位置调用它。但是,当我这样做时,代码不会像我想要的那样发送。这是我在同一个文件中创建的函数:
const validateEmail = (email) => {
return dispatch => {
// If email field is empty report alert
if (email === '') {
dispatch(addAlert('field1', 'This field is empty'));
return;
}
};
}
然后在我的emailField函数中,我只是调用:
validateEmail(email);
并且它的行为与之前的行为不同。我只是想将该代码基本移动到js函数,然后在另一个地方执行它。
答案 0 :(得分:1)
那是因为validateEmail
返回redux-thunk函数,它不执行它。
只需这样称呼它:
dispatch(validateEmail(email));
dispatch
也会传递包装函数的返回值,因此如果您想知道emailField
中的电子邮件是否有效,您可以执行以下操作:
const validateEmail = (email) => {
return dispatch => {
// If email field is empty report alert
if (email === '') {
dispatch(addAlert('field1', 'This field is empty'));
return false;
}
return true;
};
}
export const emailField = (email) => {
return dispatch => {
// Update Input
dispatch(updateInput('field1', email));
//Email validator
const isEmailValid = dispatch(validateEmail(email));
if (!isEmailValid) {
return;
}
// If all validators pass clear the alert
dispatch(deleteAlert('field1'))
};
}