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

时间:2020-04-21 11:57:24

标签: javascript reactjs state form-submit

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

handleChange在输入字段中查找更改并相应地更新状态。

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

并且状态包含{项目列表:[],当前项目:“”}

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

下面是我的完整代码

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;

2 个答案:

答案 0 :(得分:2)

这个答案可能与您的代码有些不同,但是这样可以正常工作。将按钮类型设置为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;

答案 1 :(得分:0)

setState 函数在响应中是异步,因此您不能立即获得更新的值。但是,如果需要从状态获取最近更新的值,则必须使用 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;