提交按钮需要2次点击才能生成输出

问题描述 投票:0回答:1

我仅在提交表单后才尝试更新状态。我有一个具有1个文本输入和一个提交按钮的html表单,但是需要2次单击“提交”按钮才能实际更改react状态。我正在使用2种方法handleSubmithandleChange

[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;
javascript reactjs state form-submit
1个回答
0
投票

此答案可能与您的代码有些不同,但是可以正常工作。将按钮类型设置为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;
© www.soinside.com 2019 - 2024. All rights reserved.