在React / JS中映射数组和对象后如何设置State?

我的状态为patients array。如果patient.roomroomStates.room匹配,那么我想将patient.roomStatus设置为roomStates[key].name。我的功能如下,但是我看不到为什么它不起作用。

Patient array

const patients = [
{name: "Jay”,room: "room01",roomStatus: ""},{name: "Leo”,room: "room02",{name: "Jim",room: "room05",roomStatus: ""}
]
const  roomState = { 
room01: {type: "info",name: "Stopped"},room02: {type: "normal",name: "InRoom"},room05: {type: "normal",}
   handleRoomStateChange(roomStates) {

        Object.keys(roomStates).map((key) => {
            this.state.patients.map(patient => {

                if (patient.room === roomStates[key].room) {


                    this.setState({ ...patient,roomStatus: roomStates[key].name});
                }

            })

        });
    }
Win_ky33 回答:在React / JS中映射数组和对象后如何设置State?

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

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});
};

编辑:实际上可以返回一个嵌套数组,以获得适当的数据结构,额外map可以避免:

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 });
}
本文链接:https://www.f2er.com/3142987.html

大家都在问