开发者问题收集

我如何将状态元素推送至状态数组?

2019-03-27
66

我目前正在尝试将我的状态元素 ( 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>
      )
  }
}
1个回答

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

const {results} = this.state; 
const {numbers} = results
this.setState({results:{...results,numbers:numbers.concat([event.target.value])}}
Maheer Ali
2019-03-27