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

Submit button takes 2 clicks to generate output

我试图仅在提交表单后更新反应状态。我有一个 html 表单,其中有 1 个文本输入和一个提交按钮,但需要单击 2 次提交按钮才能实际更改反应状态。我正在使用 2 种方法 handleSubmithandleChange

handleChange 查找输入字段的变化并相应地更新状态。

handleSubmithandleChange 更新的状态附加到表单提交时的数组

状态包含 { itemslist: [], currentitem: "" }

当第一次点击提交按钮时,它给出项目的先前值(或给出空数组),第二次它给出输入字段中存在值的数组。

下面是我的完整代码

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;

这个答案可能与您的代码略有不同,但它会起作用。将按钮类型设置为按钮并使按钮处理提交,而不是表单。然后将 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;

setState函数在react中是asynchronous,所以不能立即得到更新后的值。但是如果你需要从state获取最近更新的值,你必须使用setState.

callback函数
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;