Javascript 在react/JS中映射数组和对象后如何设置状态?

Javascript 在react/JS中映射数组和对象后如何设置状态?,javascript,reactjs,dictionary,setstate,Javascript,Reactjs,Dictionary,Setstate,我有一个患者数组处于状态。如果patient.room与roomStates.room匹配,则我想将patient.roomStatus设置为roomStates[key].name。我的功能如下,但我不明白为什么它不工作 Patient array const patients = [ {name: "Jay”, room: "room01", roomStatus: ""}, {name: "Leo”, room: "room02", roomStatus: ""}, {name: "

我有一个
患者数组处于状态。如果
patient.room
roomStates.room
匹配,则我想将
patient.roomStatus
设置为
roomStates[key].name
。我的功能如下,但我不明白为什么它不工作

Patient array

const patients = [
{name: "Jay”, room: "room01", roomStatus: ""}, 
{name: "Leo”, room: "room02", roomStatus: ""}, 
{name: "Jim", room: "room05", roomStatus: ""}
]

不要在每次循环迭代时设置状态,将数据保存到数组中,然后在循环执行完毕后设置:

handleRoomStateChange = roomStates => {
  const patients = Object.keys(roomStates).map(key => {
    return this.state.patients.map(patient => {
      if (patient.room === roomStates[key].room) {
        return {
          ...patient,
          roomStatus: roomStates[key].name
        };
      }
      return patient;
    });
  });

  this.setState({patients});
};
编辑:实际返回嵌套数组,要获得正确的数据结构,可以避免额外的
映射

handleRoomStateChange = roomStates => {
  const patients = this.state.patients.map(patient => {
    const roomKey = Object.keys(roomStates).find(key => key === patient.room);
    return {
      ...patient,
      roomStatus: roomStates[roomKey].name
    }
  });
  this.setState({ patients });
}

我认为您需要提供您正在使用的实际代码。我不确定
roomStates
的结构是什么(您显示了
roomState
变量,但它似乎不对应)。另外,
患者
定义中的引号是错误的unicode字符-例如,
而不是
。如果您描述所看到的行为而不是仅仅说“它不起作用”,这也会很有帮助
handleRoomStateChange = roomStates => {
  const patients = Object.keys(roomStates).map(key => {
    return this.state.patients.map(patient => {
      if (patient.room === roomStates[key].room) {
        return {
          ...patient,
          roomStatus: roomStates[key].name
        };
      }
      return patient;
    });
  });

  this.setState({patients});
};
handleRoomStateChange = roomStates => {
  const patients = this.state.patients.map(patient => {
    const roomKey = Object.keys(roomStates).find(key => key === patient.room);
    return {
      ...patient,
      roomStatus: roomStates[roomKey].name
    }
  });
  this.setState({ patients });
}