使用state确定字段是否无效

时间:2017-01-26 17:19:54

标签: javascript reactjs redux-form

我有用户名字段,如果用户在模糊后不存在于服务器中,则会显示错误消息。在重新渲染组件后,我似乎无法检索redux-form的最新道具。我需要做类似的事情:

export const asyncLogin = (values, dispatch, props) => {
    return new Promise((resolve, reject) => {
        const errors = {};
        if (!values.username || _.isEmpty(props.emailVerify)) {
            errors.username = 'Invalid username!';
        }
        resolve(errors);
    });
};

1 个答案:

答案 0 :(得分:0)

好的另一种方法是发送api请求来验证用户名,因为我无法通过asyncLogin函数获取更新的道具。我不确定这是否应该是因为我使用redux-saga中间件来发送类似的操作以更新商店,这就是为什么我试图通过更新的道具验证用户名的字段。之前发布了一个类似的问题Redux form - how to pass UPDATED props to validation function?。如果有人在这里遇到类似的问题是我如何构建我的代码(欢迎任何关于我如何即兴创作或构建我的代码的建议):

// validations/index.js
import * as api from '../services/api';

export const asyncLogin = (values) => {
    return new Promise((resolve, reject) => {
        api.appendDomain({username: values.username}).then(email => {
            api.emailVerify({email}).catch(err => {
                const errors = {};
                errors.username = 'Invalid username!';
                resolve(errors);
            });
        }).catch(errors => {
            reject();
        });
    });
};

// components/loginForm.js
const LoginForm = (props) => (
    <div className="auth-form-content">
        <form>
            <Field name="username" 
                component={UsernameField} 
                appendDomain={props.appendDomain} 
                emailVerify={props.emailVerify} 
                action={props.dispatch} 
                usernameInputVerify={true}
                placeholder="Hark, who goes there!" />
            <Field name="password" component={PasswordField} placeholder="What's the password?" />
            <button type="submit" className="waves-effect waves-light btn-large light-blue accent-4" disabled="disabled">Beam me up, Scotty.</button>
        </form>
    </div>
);

export default reduxForm({
    form: 'login',
    asyncBlurFields: ['username'],
    asyncValidate: asyncLogin
})(LoginForm);