[英]Why can't I put some of my code in another function and then call it?
I have this Redux Thunk action creator: 我有这个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'))
};
}
I want to move the Email Validator part out into its own function and then call it in the same spot where that code is now. 我想将“电子邮件验证器”部分移到其自己的函数中,然后在该代码所在的同一位置调用它。 however, when I do so the code doesn't dispatch like I want it to.
但是,当我这样做时,代码并没有像我希望的那样调度。 Here is the function I made in the same file:
这是我在同一文件中所做的功能:
const validateEmail = (email) => {
return dispatch => {
// If email field is empty report alert
if (email === '') {
dispatch(addAlert('field1', 'This field is empty'));
return;
}
};
}
Then In my emailField function, I just call: 然后在我的emailField函数中,我只调用:
validateEmail(email);
and it doesn't behave the same as it did before. 而且它的行为与以前不同。 I simply want to do a basic move of that code to a js function then execute it in another place.
我只是想将代码移至js函数的基本步骤,然后在另一个地方执行它。
That's because validateEmail
returns redux-thunk function, it does not execute it. 那是因为
validateEmail
返回redux-thunk函数,但不执行它。
Just call it this way: 只是这样称呼它:
dispatch(validateEmail(email));
dispatch
also passes up the return value of the wrapped function, so if you want to know that an email is valid or not in emailField
you might do the following: 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'))
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.