当我尝试更新时,输入字段将取消选择

时间:2018-08-07 06:04:21

标签: reactjs

我正在尝试更新表单上的输入值。我需要更新的输入值位于另一个对象数组中的一个对象数组中。我正在尝试更新电子邮件中的地址(请参见下文)。

const userProfiles = [{
firstName: 'John',
emails: [{ address: 'john@gmail.com' }]
}]

每次击键都会更新userProfiles的字段和状态,但是输入字段会脱离。因此,我必须继续重新选择输入字段。我在这里想念什么?

handleInputChange = (userProfileId, index) => (event) => {
  const target = event.target;
  const value = target.value;
  const name = target.name;

  const userProfiles = this.state.userProfiles.map((userProfile) => {
    if (userProfile._id === userProfileId) {
      if (name === 'email') {
        const emails = userProfile.emails.map((email, idx) => {
          if (idx === index) {
            return {
              ...email,
              address: value,
            };
          }
          return {
            ...email,
          };
        });

        return {
          ...userProfile,
          emails,
        };
      }

      return {
        ...userProfile,
        [name]: value,
      };
    }
    return {
      ...userProfile,
    };
  });

  this.setState({
    userProfiles,
  });
}

1 个答案:

答案 0 :(得分:0)

handleInputChange = (userProfileId, index) => (event) => {
    const target = event.target;
    const value = target.value;
    const name = target.name;

    let { userProfiles } = this.state;
    userProfiles.map((eachProfile) => {
        let { emails } = userProfiles.emails;
        if (userProfile._id === userProfileId) {
            if(name === 'email') {
                emails.map((emails, idx) => {
                    if (idx === index) {
                        emails = value;
                    }
                })
            }
        }
    });
    this.setState({
        ...this.state,
        userProfiles
    })
}

你可以试试这个吗?