简体   繁体   English

你如何更新 React 组件状态中对象的单个属性?

[英]How do you update individual properties of objects in React component states?

I am creating a simple React app that allows the user to add contacts to a master list.我正在创建一个简单的 React 应用程序,它允许用户将联系人添加到主列表。 My components state looks like this:我的组件 state 看起来像这样:

state = {
        contact: {
            fname: "",
            lname: "",
            address: "",
            phone: "",
            email: "",
            id: ""
        }
    };

So far, I have been able to effectively add properties such as name, email, etc using values sent from inputs.到目前为止,我已经能够使用从输入发送的值有效地添加名称、email 等属性。

this.setState({
    contact: {
        ...this.state.contact,
        [e.target.name]: e.target.value // e is an event sent from an input
    }
});
    };

That's all fine and dandy, but I need each contact to have a unique ID.这一切都很好,但我需要每个联系人都有一个唯一的 ID。 I have been trying to tack on the ID to the contact object before I send it up the component hierarchy.在将 ID 发送到组件层次结构之前,我一直在尝试将 ID 添加到联系人 object。

const unId = new Date().getTime();
this.setState({
    contact: {
        ...this.state.contact,
        id: unId
    }
});

This code is producing some strange issues and I'm not sure why.这段代码产生了一些奇怪的问题,我不知道为什么。 When I run it for the first time, the id is generated, but not assigned to the contact.当我第一次运行它时,会生成 id,但没有分配给联系人。 The second time I run it, the id produced the first time is assigned to the second contact.我第二次运行它时,第一次生成的 id 被分配给第二个联系人。 In other words, the id property is updating the state later one cycle behind the time it should.换句话说,id 属性在比它应该的时间晚一个周期后更新 state。

I'm not very familiar with synchronicity or anything in React, so I would really appreciate any help I could get.我对同步性或 React 中的任何东西都不是很熟悉,所以我非常感谢我能得到的任何帮助。

Does this example help you?这个例子对你有帮助吗? If not, can you comment what do you exactly want?如果没有,你能评论你到底想要什么吗?

https://codesandbox.io/s/priceless-mccarthy-7i69e https://codesandbox.io/s/priceless-mccarthy-7i69e

import React, { Component } from "react";

class App extends Component {
  state = {
    contact: {
      fname: "",
      lname: "",
      address: "",
      phone: "",
      email: "",
      id: new Date().getTime()
    }
  };

  handleInputChange = e => {
    this.setState({
      contact: {
        ...this.state.contact,
        [e.target.name]: e.target.value
      }
    });
  };

  handleSubmit = e => {
    console.log(this.state);
  };

  render() {
    const { fname, lname, address, phone, email, id } = this.state.contact;

    return (
      <div>
        <label>fname</label>
        <input
          type="text"
          value={fname}
          name="fname"
          onChange={this.handleInputChange}
        />
        <br />
        <label>lname</label>
        <input
          type="text"
          value={lname}
          name="lname"
          onChange={this.handleInputChange}
        />
          <br />
        <label>address</label>
        <input
          type="text"
          value={address}
          name="address"
          onChange={this.handleInputChange}
        />
          <br />
        <label>phone</label>
        <input
          type="text"
          value={phone}
          name="phone"
          onChange={this.handleInputChange}
        />
          <br />
        <label>email</label>
        <input
          type="text"
          value={email}
          name="email"
          onChange={this.handleInputChange}
        />
          <br />
        <label>id</label>
        <input
          type="text"
          value={id}
          name="id"
          onChange={this.handleInputChange}
        />
        <button type="button" onClick={this.handleSubmit}>
          Submit
        </button>
        <hr />
        {
          JSON.stringify(this.state)
        }
      </div>
    );
  }
}

export default App;

The ID isn't created until the next render because the component's state isn't initialized when it gets created. ID 在下一次渲染之前不会创建,因为组件的 state 在创建时未初始化。 You need to initialize its state.您需要初始化它的 state。

Either in a class constructor在 class 构造函数中

    constructor() {
      super();
      this.state = {
        id: new Date().getTime()
      }
    }

or a state attribute或 state 属性

    state = {
      id: new Date().getTime()
    }

Here is a working codepen example这是一个有效的代码笔示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM