gpt4 book ai didi

javascript - 从 handleSubmit 函数抛出 redux-form 提交错误

转载 作者:行者123 更新时间:2023-11-29 10:06:19 24 4
gpt4 key购买 nike

我有一个 redux-form,它有一个 handleSubmit 函数,我用它来进行一些异步 http 服务器身份验证。如果身份验证由于某种原因失败,我想抛出一个 redux-form 错误。如果我抛出“SubmissionError”,我会收到一条错误消息:Uncaught (in promise)

我的代码:

class MyLoginForm extends Component {
    handleSubmit({ email, password }) {
        axios.post("http://API_SERVER/login", null, { withCredentials: true, auth: { username: email, password: password } })
            .then((response) => {
                console.log('HTTP call success. JWT Token is:', response.data);
            })
            .catch(err => {
                console.log(err)
>>>> WHAT TO DO TO CONVEY THE ERROR IN THE REDUX-FORM <<<<
                if (err.response) {
                    
                    if (err.response.status !== 200) {
                        console.log("Unexpected error code from the API server", err.response.status);
                        throw new SubmissionError({ _error: 'HTTP Error. Possibly invalid username / password' });
                    }
                    return
                }
                throw new SubmissionError({ _error: 'HTTP Error. Please contact Helpdesk' });
            });
    }

    render() {
        const { error, handleSubmit, pristine, reset, submitting } = this.props
        return (
            <form onSubmit={handleSubmit(this.handleSubmit.bind(this))}>
                <Field name="email" type="email" component={renderField} label="Email Address" />
                <Field name="password" type="password" component={renderField} label="Password" />
                {error && <strong>{error}</strong>}
                <div>
                    <button type="submit" disabled={submitting}>Log In</button>
                    <button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button>
                </div>
            </form>
        )
    }
}

export default connect(null, actions)(reduxForm({
    form: ‘MyLoginForm' // a unique identifier for this form
})(MyLoginForm));

我想要一个解决方案来更新/呈现 redux-form 本身的错误消息,而无需在全局状态、reducer 等中创建任何内容。

最佳答案

解决方法很简单。我只需在 axios 调用前添加一个 return 即可。所以更新后的代码将是这样的:

handleSubmit({ email, password }) {
return axios.post("http://API_SERVER/login", null, { withCredentials: true, auth: { username: email, password: password } })
.then((response) => {
console.log('HTTP call success. JWT Token is:', response.data);
})

关于javascript - 从 handleSubmit 函数抛出 redux-form 提交错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42575288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com