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

时间:2019-11-07 16:46:22

标签: javascript reactjs dictionary setstate

我的状态为patients array。如果patient.roomroomStates.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: ""}
]
const  roomState = { 
room01: {type: "info", room: "room01", name: "Stopped"},
room02: {type: "normal",room: "room02", name: "InRoom"},
room05: {type: "normal", room: "room05",name: "InRoom"},
}
   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});
                }

            })

        });
    }

1 个答案:

答案 0 :(得分:1)

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

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