设置对象数组的状态

时间:2018-05-09 05:17:29

标签: reactjs

我有一个具有名为Report的状态属性的react组件。它符合以下界面:

interface Report {
  firstname: string;
  lastname: string;
  otherinfo: info[];
}

interface info {
  dob: string;
  gender: string;
  email: string;
}

如果我想更新setState的值,我想知道执行email的首选方式。

2 个答案:

答案 0 :(得分:0)

我相信这样的事情应该有用。

const targetIndex = 0; // assuming this is the index of the element you want to update
const newEmail = 'email@example.com'; // new email address to be set

this.setState(prevState => ({
  ...prevState,
  report: {
    ...prevState.report,
    otherinfo: prevState.report.otherinfo.reduce((accum: info[], currrent: info, currentIndex: number) => {
      if (currentIndex === targetIndex) { // this is where we're trying to find the element with the matching index
        return [
          ...accum,
          {
            ...current,
            email: newEmail, // this is where we set the new email
          }
        ]
      }
      return [...accum, current];
    }, [])
  }
}));

答案 1 :(得分:0)

我想知道您是否可以将Immutability-helper用于您的用例?有点像:

const newReport = update(report, { otherinfo: { email: { $set: newEmail }}}); this.setState({report: newReport})

相关问题