减速器未更新

时间:2018-11-15 05:05:30

标签: reactjs react-native redux react-redux immutability

我试图更新嵌套在我的化简器状态数组中的对象的属性。减速器收到了很好的有效载荷,但是我的视图没有得到更新。

这是我要执行的操作的摘要:

//reducers.js

case UPDATE_ROOM_TMP: {
  const roomIndex = state.config.rooms.findIndex(room => room.id === action.payload.id);
  return { 
    ...state, 
    rooms: state.config.rooms.map(
      (room, i) => i === roomIndex ? { ...room, tmp : action.payload.tmp} : room
    )
  }
}

这是reducer状态的结构:

config: {
  ...
  rooms: [
    {
      ...,
      tmp: 22
    }
  ]
}

更新减速器的动作:

export const updateRoomTmp = ({ targetTmp, roomId }) => {
  return {
    type: UPDATE_ROOM_TMP,
    payload: { targetTmp, roomId },
  };
};

调用动作的函数:

  increaseTmp = () => {
    const tmp = this.props.config.rooms[this.roomIndex].targetTmp + 1
    this.props.updateRoomTmp({targetTmp: tmp, roomId: this.props.room.id});
  }

呈现新值的文本

  <Text>{this.props.config.rooms[this.roomIndex].targetTmp}</Text>

我如何连接到配置:

const mapStateToProp = ({ allConfig }, props) => {
  const { config } = allConfig;
  return { config };
 };

所以问题是,当调用crementTmp时,reducer会收到有效的有效负载,但永远不会更新,因此文本也不会更新。

1 个答案:

答案 0 :(得分:0)

尝试像这样更改reducers.js

case UPDATE_ROOM_TMP: {
const roomIndex = state.config.rooms.findIndex(room => room.id ===action.payload.id);
    return { 
            ...state, 
            config:{
            ...config,
            rooms: state.config.rooms.map( (room, i) => i === roomIndex ? { ...room, tmp : action.payload.tmp} : room)
            }
    }
}