我仅在提交表单后才尝试更新状态。我有一个具有1个文本输入和一个提交按钮的html表单,但是需要2次单击“提交”按钮才能实际更改react状态。我正在使用2种方法handleSubmit
和handleChange
。
[handleChange
在输入字段中查找更改并相应地更新状态。
[handleSubmit
将由handleChange
更新的状态附加到表单提交时的数组中
并且状态包含{项目列表:[],当前项目:“”}]
单击第一次提交按钮时,它将给出项目的先前值(或给出空数组),而在第二次单击时,它将给出在输入字段中存在值的数组。
下面是我的完整代码
import React from 'react';
class App extends React.Component{
constructor(){
super()
this.state = {
currentitem: '',
itemslist: []
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit(event){
event.preventDefault();
this.setState((prevState) => {
return{
itemslist: prevState.itemslist.concat([this.state.currentitem])
}
})
console.log(this.state.items)
}
handleChange(event){
const {name, value} = event.target
this.setState({ [name] : value })
console.log(this.state.currentitem)
}
render(){
return(
<div>
<form onSubmit={this.handleSubmit} >
<input type='text' placeholder='enter text' name='currentitem' onChange={this.handleChange} value={this.state.currentitem} />
<button type='submit'>Submit</button>
</form>
</div>
)
}
}
export default App;
此答案可能与您的代码有些不同,但是可以正常工作。将按钮类型设置为button并使按钮处理提交,而不是表单。然后将handleSubmit函数更改为我所拥有的。我已经尝试过了,它确实有效!:
import React from 'react';
class App extends React.Component{
constructor(){
super()
this.state = {
currentitem: '',
itemslist: []
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit(e){
e.preventDefault();
const { currentitem, itemslist } = this.state;
const newArray = [
...itemslist,
currentitem
];
this.setState({ itemslist, newArray });
}
handleChange(event){
const {name, value} = event.target
this.setState({ [name] : value })
console.log(this.state.currentitem)
}
render(){
return(
<div>
<form>
<input type='text' placeholder='enter text' name='currentitem' onChange={this.handleChange} value={this.state.currentitem} />
<button type='button' onClick={this.handleSubmit}>Submit</button>
</form>
// In cas eyou want to see the values in the array+
{
this.state.itemsList.map((item) => <p>{item}</>)
}
</div>
)
}
}
export default App;