我正在尝试使用redux表单注册用户。所有同步验证都有效,但问题出现在用户提交表单并且电子邮件已经注册时。返回一个错误,我可以按如下方式访问
export function registerUser(details, callback) {
return(dispatch) =>{
dispatch(startRegisteing());
axios.post(URL, {
"email": details['email'],
"name": details['username'],
"password": details['password']
}).then((data) =>{
callback();
dispatch(RegistrationSuccessfull(data))
}).catch((error) => {
console.log('error', error.response.data.message);
//throw new SubmissionError(error.response.data.message);
dispatch(RegistrationFailed(error.response.data.message))
})
}
}
RegistrationFailed
操作
export function RegistrationFailed(error) {
return{
type: types.REGISTRATION_ERROR,
payload:error
}
}
它的reducer只是更新状态
switch (action.type){
case types.REGISTRATION_SUCCESSFUL:
console.log("nanana too ", action);
return{
...state, isRegisteringUser:false,
data:action.data
};
case types.REGISTRATION_ERROR:
console.log("current state", state);
return{
...state, error: action.payload
}
}
我的问题是如何能够以
的形式向用户显示此错误<form onSubmit={handleSubmit(this.onFormSubmit.bind(this))}>
<Field
name="username"
lable="Username"
type="text"
component={ this.renderField }
/>
<Field
name="email"
type="email"
lable="Email"
component={ this.renderField }
/>
{// I want to present the error here }
{error && <strong>{error}</strong>}
<Field
name="password"
type="password"
lable="Password"
component={ this.renderField }
/>
<Field
name="confirm_password"
type="password"
lable="Confirm Password"
component={ this.renderField }
/>
<button type="submit" className="btn btn-primary" disabled={submitting}>Register</button>
<Link className="btn btn-danger" to="/login">Cancel</Link>
</form>
我已经尝试throw new SubmissionError(error.response.data.message);
作为反应形式文档说但是它引发了Unhandled rejection SubmissionError: Submit Validation Failed
的错误
注意:我是react-redux的初学者。任何帮助将不胜感激
答案 0 :(得分:0)
由于您将错误存储在redux存储中的状态的error
字段中,因此您可以使用mapStateToProps
在表单中订阅此字段,并在字段不为null时显示该消息
...
import ...
...
class YourComponent extends React.Component{
render(){
return(
<form onSubmit={handleSubmit(this.onFormSubmit.bind(this))}>
<Field
name="username"
lable="Username"
type="text"
component={ this.renderField }
/>
<Field
name="email"
type="email"
lable="Email"
component={ this.renderField }
/>
{this.state.yourReducer.error && <strong>{this.state.yourReducer.error}</strong>}
<Field
name="password"
type="password"
lable="Password"
component={ this.renderField }
/>
<Field
name="confirm_password"
type="password"
lable="Confirm Password"
component={ this.renderField }
/>
<button type="submit" className="btn btn-primary" disabled={submitting}>Register</button>
<Link className="btn btn-danger" to="/login">Cancel</Link>
</form>
);
}
}
const mapStateToProps=(state) =>{
"yourReducer": state.yourReducer
}
export default connect(mapStateToProps)(YourComponent);
答案 1 :(得分:0)
您可以使用mapStateToProps将商店绑定到组件内的props,然后您就可以直接在商店中使用this.props并显示错误。