在React-Native中调用Object.assign时Redux存储状态不会更新

时间:2020-06-09 04:18:44

标签: react-native redux websocket

我正在开发基于React Native的应用程序。

这是我的代码,UPDATE_MY_CONNECTION_ID按预期工作,并在分派时更新状态。 UPDATE_ROOM但是根本不更新状态。它可以到达console.log(tmp)

const initialState = {
  playerOne: "",
  playerTwo: "",
  connectionIdArr: [],
  myConnectionId: "",
};

const reducer = (state = initialState, action) => {
 switch (action.type) {
    case "UPDATE_MY_CONNECTION_ID":
      return Object.assign({}, state, {
        myConnectionId: action.payload.myConnectionId,
      });
    case "UPDATE_ROOM":
      console.log(
        "updating room after receiving broadcast from room player",
        action.payload
      );
      Axios.get(
        `${process.env.API_ENDPOINT}/get_room/${action.payload.match_id}`
      )
        .then((res) => {
          const tmp = {};
          if (res.data.players[0] && res.data.players[0].length > 0)
            tmp.playerOne = res.data.players[0];
          if (res.data.players[1] && res.data.players[1].length > 0)
            tmp.playerTwo = res.data.players[1];
          tmp.connectionIdArr = [...res.data.connections];
          console.log(tmp);
          return Object.assign({}, state, tmp);
        })
        .catch((err) => console.log("error UPDATE_ROOM: ", err));
    default:
       etc etc etc...

1 个答案:

答案 0 :(得分:2)

您永远不要在减少器中使用异步请求,如果您确实想执行异步请求,那么redux-thunk是一个不错的选择,或者是redux-saga。我建议您对两者进行一下选择,然后选择适合您需求的一种。

Redux-Saga

Redux-Thunk