【问题标题】:Question on adding a input value to an array using setState关于使用 setState 将输入值添加到数组的问题
【发布时间】:2021-11-22 05:47:35
【问题描述】:

我正在尝试使用 setState 通过基本的 HTML 输入来更新 React 中的状态数组。 我尝试更新的状态如下:

 "businessName": "",
  "grossAnnualSales": 0,
  "contactEmail": "",
  "numEmployees": 0,
  "annualPayroll": 0,
  "locations": [{"zip": ""}],
  "industryId": "",

我需要将用户在 React 组件中输入的邮政编码添加到数组中的这个对象中。

到目前为止,我已经尝试过了,但它不起作用,它只是更新为字符串而不是数组:

updateZip(){
return e => this.setState({"locations": [{"zip": e.currentTarget.value}]}) 

}

React 组件:

<input onChange={this.updateZip()} type="text" className="zip-input"/>

如何成功更新状态?

【问题讨论】:

    标签: javascript reactjs react-redux


    【解决方案1】:

    使用 e.target.value 并传递 onChange={this.updateZip}

       class App extends Component {
      state = {
        locations: [{ zip: "" }]
      };
      updateZip = (e) => {
        this.setState({ locations: [{ zip: e.target.value }] });
      };
    
      render() {
        return (
          <div>
            <input onChange={this.updateZip} type="text" className="zip-input" />
            <p>{this.state.locations[0].zip}</p>
          </div>
        );
      }
    }
    export default App;
    

    CodeSandBox

    【讨论】:

    • 这就是我在代码中所做的,但它不起作用,它会在我的状态下创建一个新的未定义键。
    • 你需要获取e作为参数
    • 你这是什么意思?
    • 我编辑了我的答案,请再检查一遍
    • 知道了,但它仍然不起作用。它创建一个名为 undefined 状态的新键,并将用户输入作为字符串值添加到它。
    【解决方案2】:

    尝试用箭头函数替换您的 updateZip 函数。

    updateZip = (e) => {
        return e => this.setState({"locations": [{"zip": e.currentTarget.value}]}) }
    

    还有

    <input onChange={(e) => this.updateZip(e)} type="text" className="zip-input"/>
    

    【讨论】:

    • 它现在没有用箭头函数更新所以不起作用。
    • 有一种解决方法,而不是直接更新位置中的 zip,而是尝试更新位置键。示例:- 让 loc = [{zip: ""}]; loc[0].zip = ;位置 = 位置;
    猜你喜欢
    • 1970-01-01
    • 2021-08-01
    • 2021-03-04
    • 2019-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    相关资源
    最近更新 更多