【发布时间】:2020-03-24 08:09:53
【问题描述】:
我正在使用 React 16.12.0。我试图弄清楚如何处理和显示从我的服务器返回的验证错误。我已经设置了这个表单...
import React, {Component} from 'react';
import {FormControl, FormGroup} from 'react-bootstrap';
/* Import Components */
import Input from '../components/Input';
import Country from '../components/Country';
import Province from '../components/Province';
import Button from '../components/Button'
class FormContainer extends Component {
statics: {
DEFAULT_COUNTRY: 484;
}
constructor(props) {
super(props);
this.state = {
countries: [],
provinces: [],
newCoop: {
name: '',
type: {
name: ''
},
address: {
formatted: '',
locality: {
name: '',
postal_code: '',
state: ''
},
country: 484, //FormContainer.DEFAULT_COUNTRY,
},
enabled: true,
email: '',
phone: '',
web_site: ''
},
}
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.handleClearForm = this.handleClearForm.bind(this);
this.handleInput = this.handleInput.bind(this);
}
/* This life cycle hook gets executed when the component mounts */
handleFormSubmit(e) {
e.preventDefault();
const NC = this.state.newCoop;
delete NC.address.country;
fetch('/coops/',{
method: "POST",
body: JSON.stringify(this.state.newCoop),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
}).then(response => {
response.json().then(data =>{
console.log("Successful" + data);
})
})
}
handleClearForm() {
// Logic for resetting the form
}
handleInput(e) {
let self=this
let value = e.target.value;
console.log("value:" + value);
let name = e.target.name;
//update State
this.setValue(self.state.newCoop,name,value)
}
setValue = (obj,is, value) => {
if (typeof is == 'string')
return this.setValue(obj,is.split('.'), value);
else if (is.length === 1 && value!==undefined)
return this.setState({obj: obj[is[0]] = value});
else if (is.length === 0)
return obj;
else
return this.setValue(obj[is[0]],is.slice(1), value);
}
render() {
return (
<form className="container-fluid" onSubmit={this.handleFormSubmit}>
<FormGroup
controlId="formBasicText">
<Input inputType={'text'}
title= {'Name'}
name= {'name'}
value={this.state.newCoop.name}
placeholder = {'Enter cooperative name'}
handleChange = {this.handleInput}
/> {/* Name of the cooperative */}
<Input inputType={'text'}
title= {'Type'}
name= {'type.name'}
value={this.state.newCoop.type.name}
placeholder = {'Enter cooperative type'}
handleChange = {this.handleInput}
/> {/* Type of the cooperative */}
<Input inputType={'text'}
title= {'Street'}
name= {'address.formatted'}
value={this.state.newCoop.address.formatted}
placeholder = {'Enter address street'}
handleChange = {this.handleInput}
/> {/* Address street of the cooperative */}
<Input inputType={'text'}
title= {'City'}
name= {'address.locality.name'}
value={this.state.newCoop.address.locality.name}
placeholder = {'Enter address city'}
handleChange = {this.handleInput}
/> {/* Address city of the cooperative */}
<Country title={'Country'}
name={'address.country'}
options = {this.state.countries}
value = {this.state.newCoop.address.country}
placeholder = {'Select Country'}
handleChange = {this.handleInput}
/> {/* Country Selection */}
<Province title={'State'}
name={'address.locality.state'}
options = {this.state.provinces}
value = {this.state.newCoop.address.locality.state}
placeholder = {'Select State'}
handleChange = {this.handleInput}
/> {/* State Selection */}
<Input inputType={'text'}
title= {'Postal Code'}
name= {'address.locality.postal_code'}
value={this.state.newCoop.address.locality.postal_code}
placeholder = {'Enter postal code'}
handleChange = {this.handleInput}
/> {/* Address postal code of the cooperative */}
<Input inputType={'text'}
title= {'Email'}
name= {'email'}
value={this.state.newCoop.email}
placeholder = {'Enter email'}
handleChange = {this.handleInput}
/> {/* Email of the cooperative */}
<Input inputType={'text'}
title= {'Phone'}
name= {'phone'}
value={this.state.newCoop.phone}
placeholder = {'Enter phone number'}
handleChange = {this.handleInput}
/> {/* Phone number of the cooperative */}
<Input inputType={'text'}
title= {'Web Site'}
name= {'web_site'}
value={this.state.newCoop.web_site}
placeholder = {'Enter web site'}
handleChange = {this.handleInput}
/> {/* Web site of the cooperative */}
<Button
action = {this.handleFormSubmit}
type = {'primary'}
title = {'Submit'}
style={buttonStyle}
/> { /*Submit */ }
<Button
action = {this.handleClearForm}
type = {'secondary'}
title = {'Clear'}
style={buttonStyle}
/> {/* Clear the form */}
</FormGroup>
</form>
);
}
componentDidMount() {
let initialCountries = [];
let initialProvinces = [];
// Get initial countries
fetch('/countries/')
.then(response => {
return response.json();
}).then(data => {
initialCountries = data.map((country) => {
return country
});
console.log("output ...");
console.log(initialCountries);
this.setState({
countries: initialCountries,
});
});
// Get initial provinces (states)
fetch('/states/484/')
.then(response => {
return response.json();
}).then(data => {
console.log(data);
initialProvinces = data.map((province) => {
return province
});
this.setState({
provinces: initialProvinces,
});
});
}
}
const buttonStyle = {
margin : '10px 10px 10px 10px'
}
export default FormContainer;
当服务器(一个 Django Python 应用程序)无法处理表单时,它会返回一个 400 响应正文,其中包含与每个字段相关联的错误。例如,这样的响应正文看起来像
{"phone":["The phone number entered is not valid."]}
捕获此错误并将其显示在我的表单中的正确方法是什么?我见过的所有示例都在提交表单之前处理验证 - 例如在结束之前在“handleFormSubmit”处理程序中编写“validateFields”方法或类似的东西。
编辑:添加了新的 fetch 方法以响应 cmets。当获取请求返回 400 时,添加“catch”块不会显示错误。
fetch('/coops/',{
method: "POST",
body: JSON.stringify(this.state.newCoop),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
}).then(response => {
response.json().then(data =>{
console.log("Successful" + data);
})
}).catch(error => console.log(error))
CHrome 开发控制台在请求中报告 400 以及
FormContainer.jsx:54 Fetch failed loading: POST "http://localhost:3000/coops/".
此外,尽管 400 和 Chrome 报告的内容,“成功”console.log 消息仍会打印出来。
【问题讨论】:
-
嗯,表单字段验证发生在表单提交之前,但听起来您是在询问是否显示表单处理错误。据推测,这些错误将作为来自
fetch的 Promise 拒绝返回。您能否确认您在代码中收到错误的位置。从那里他们可以显示几乎任何你想要的方式。您预期的错误 UI 是什么? (表格上方的错误列表?每个字段下方的一些持有人错误文本?等等...)你能用这些细节更新你的问题吗? -
嗨@DrewReese,我想这是我的问题——我应该在我的代码中哪里捕获从我的表单提交返回的错误并显示它们?我假设它在我拥有的 handleFormSubmit 函数中,但我并不完全清楚。也不确定返回我的错误的结构是否最适合做出反应,所以我也愿意探索改变它。
-
将
.catch(error => console.log(error));块添加到fetch返回的promise 链中,并尝试提交您知道应该失败并返回错误的表单数据。如果我的直觉是正确的,您应该会看到它们记录在 catch 块中。如果返回的错误有一个很好的方法将它们关联回几乎任何形状都可以工作的表单字段;你所拥有的似乎足够了。一旦我们确认您收到错误的位置,我们就可以弄清楚如何显示它们。 -
感谢您一直以来的帮助。我编辑了我的问题以显示我将“catch”块放在哪里,尽管它没有被调用。虽然我可以在控制台中看到服务器返回 400,但 console.log 成功消息仍在继续打印出来。
-
啊,我的错误,似乎
fetch不会reject on http error status。实际上,您会将它们放在“已解决”分支中,但需要检查response.ok(200-299),其他任何东西都可能具有您需要的错误状态,可能是response.statusText,但这完全取决于您的服务器打包方式起来。
标签: reactjs forms validation form-submit