2 回答

TA貢獻1752條經驗 獲得超4個贊
這個答案可能與您的代碼有點不同,但這樣它就可以工作。將按鈕類型設置為按鈕并使按鈕處理提交,而不是表單。然后將 handleSubmit 函數更改為我所擁有的。我已經嘗試過了,它確實有效?。?/p>
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;

TA貢獻2016條經驗 獲得超9個贊
setState函數在 react 中是異步的,因此您無法立即獲取更新的值。但是如果你需要從 state 中獲取最近更新的值,你必須使用setState的回調函數。
this.setState({items: newItems}, () => { console.log(); })
我已經修改了您的示例,如下所示以滿足您的要求。
import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = {
currentitem: '',
items: []
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
this.setState((prevState) => {
return {
items: prevState.items.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;
添加回答
舉報