Reactjs React-此.state未在提交时更新
我是新来的 我在处理表单提交时遇到问题。这是我的代码:Reactjs React-此.state未在提交时更新,reactjs,Reactjs,我是新来的 我在处理表单提交时遇到问题。这是我的代码: class EditCoffee extends Component{ constructor (props) { super(props); this.state = { coffeeshop:'', bean:'', seeds:'', formData: { aroma:'', flavor:'',
class EditCoffee extends Component{
constructor (props) {
super(props);
this.state = {
coffeeshop:'',
bean:'',
seeds:'',
formData: {
aroma:'',
flavor:'',
acidity:'',
body:'',
color:''
},
};
this.handleCoffeeComponentsFormChange = this.handleCoffeeComponentsFormChange.bind(this);
};
这就是所谓的onSubmit()
:
这应该会更新这个。状态:
handleCoffeeComponentsFormChange(event) {
const obj = this.state.formData;
obj[event.target.name] = event.target.value;
this.setState(obj);
console.log(this.state.formData)
this.validateForm();
};
此处发生错误,因为未更新this.state.formData.aroma
:
getAroma(event) {
const {userId, select} = this.props
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/coffee-aroma/${select}/${this.state.formData.aroma}/${userId}`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
return axios(options)
.then((res) => {
console.log(res.data.message)
console.log(options.url)
})
.catch((error) => { console.log(error); });
};
render(){
return (
<div>
<h1 className="title is-1">Edit Coffee</font></h1>
<h1 className="title is-1">{ this.Capitalize('Aroma') }</h1>
<form onSubmit={ (event) => this.handleEditAroma(event) }>
<div className="field">
<input
name="aroma"
className="input is-dark is-large"
type="text"
placeholder="Enter value from 0.0 to 1.0"
//value={this.state.formData.aroma}
onChange={this.handleCoffeeComponentsFormChange}
/>
</div>
<input
type="submit"
className="button is-dark is-small is-fullwidth"
value="Submit"
/>
</form>
但当我点击“提交按钮”时,我在控制台上得到了这个错误:
"GET /coffee-aroma/decaf//1 HTTP/1.0" 404 -
其中状态值为空(//),提交时不更新。我遗漏了什么?尝试通过以下方式更新您的状态:
HandleOffeeComponentsFormChange
handleCoffeeComponentsFormChange(event) {
this.setState(prev => ({
...prev,
formData: {
...prev.formData,
[`${event.target.name}`]: event.target.value
}
})
this.validateForm();
};
对不起,这是个愚蠢的错误 在
thisgetAroma()
之前,我接到了这个电话:
this.clearForm()
这显然会将所有更新的状态清除回'
很抱歉给您带来不便。您不应该更改状态,请参考您能指出错误吗?我还怀疑
url:
${process.env.REACT\u APP\u WEB\u SERVICE\u url}/coffee aroma/${select}/${this.state.formData.aroma}/${userId},
没有指向localhost:3000
,这通常是webpack dev服务器在使用create react app时设置的。服务器上的set CORS标头或Nginx代理已配置。所有其他URL都在工作它不工作,因为状态未更新,并且在上找不到确切路径。请使用完整的HandleOfficeComponentsFormChange()
?我正在用您的解决方案获取语法错误。但是您没有使用HandleOffeeComponents FormChange(event){..仍然获取错误语法错误:意外标记,预期“,”(425:4)
,上面formData
前面的后面缺少一个逗号
"GET /coffee-aroma/decaf//1 HTTP/1.0" 404 -
handleCoffeeComponentsFormChange(event) {
this.setState(prev => ({
...prev,
formData: {
...prev.formData,
[`${event.target.name}`]: event.target.value
}
})
this.validateForm();
};