gpt4 book ai didi

javascript - 如何将状态元素推送到状态数组?

转载 作者:行者123 更新时间:2023-12-02 23:56:10 26 4
gpt4 key购买 nike

我目前正在尝试将我的状态元素 (user_number_X) 推送到数组 (this.state.results.numbers),但我的输入处理函数无法正常工作.

如何重写它以便将输入值推送到数组中?

这是我的代码:

export default class InputArea extends React.Component {
constructor(props){
super(props);
this.state = {
draw_number: '',
user_number_1: '',
user_number_2: '',
user_number_3: '',
user_number_4: '',
user_number_5: '',
user_number_6: '',
results : {
numbers: [],
draws: ''
}
}
}

/* handledrawsChange = event => {
this.setState({
event
})
} */

inputHandler = event => {
this.setState({[event.target.name]: event.target.value});
this.state.results.numbers.push(event.target.value)
// this.state.results.numbers.push(event.target.value)//this.setState({number: this.state.results.numbers.push(parseInt(event.target.value))});
}

componentDidMount() {
fetch("http://localhost:8080/simulate", {
method: "POST",
body: this.state.results
});
}


render() {
console.log(this.state);
return (
<InputField>
<InputWrapper>
<Label>1st number</Label>
<Input name="user_number_1" type="number" maxlength="2" value={this.state.user_number_1} onChange={this.inputHandler} required></Input>
<Label>2nd number</Label>
<Input name="user_number_2" type="number" maxlength="2" value={this.state.user_number_2} onChange={this.inputHandler} required></Input>
<Label>3rd number</Label>
<Input name="user_number_3" type="number" maxlength="2" value={this.state.user_number_3} onChange={this.inputHandler} required></Input>
<Label>4th number</Label>
<Input name="user_number_4" type="number" maxlength="2" value={this.state.user_number_4} onChange={this.inputHandler} required></Input>
<Label>5th number</Label>
<Input name="user_number_5" type="number" maxlength="2" value={this.state.user_number_5} onChange={this.inputHandler} required></Input>
<Label>6th number</Label>
<Input name="user_number_6" type="number" maxlength="2" value={this.state.user_number_6} onChange={this.inputHandler} required></Input>
<Label>Number of draws:</Label>
<Input name="draw_number" type="number" value={this.state.draw_number} onChange={this.inputHandler} required></Input>
</InputWrapper>
<Button type="submit" /*onClick={this.drawsHandler}*/>Let's win!</Button>
</InputField>
)
}
}

最佳答案

您可以使用 concat() 来实现这一点,并使用对象解构来获得更简洁的代码

const {results} = this.state; 
const {numbers} = results
this.setState({results:{...results,numbers:numbers.concat([event.target.value])}}

关于javascript - 如何将状态元素推送到状态数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55376141/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com