【问题标题】:Submit button takes 2 clicks to generate output提交按钮需要点击 2 次才能生成输出
【发布时间】:2020-04-21 11:57:24
【问题描述】:

我正在尝试仅在提交表单后更新状态。我有一个 html 表单,它有 1 个文本输入和一个提交按钮,但是需要点击 2 次提交按钮才能真正改变反应中的状态。我正在使用handleSubmithandleChange 两种方法。

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

handleSubmit 在表单提交时将handleChange 更新的状态追加到数组中

并且状态包含 { 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;

【问题讨论】:

  • React 中的状态设置是异步的,所以你不能在下一行 console.log 它并期望它被更新
  • @Jayce444 是对的,如果你想检查 currentItem 的值,那么你应该将它记录在你的渲染方法中,这样你就可以在每次渲染时看到它的更新。
  • @JoeLloyd 谢谢,它在渲染方法中显示输出。

标签: javascript reactjs state form-submit


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    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;
    

    【讨论】:

      猜你喜欢
      • 2019-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      相关资源
      最近更新 更多