如何从 reducer 获取 React Redux 状态值?

How to get a React Redux state value from the reducer?

在 Redux 中,我目前的状态如下所示。

{
  activeConversation: "Jim"
  conversations: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
}

我也在使用 socket.io 向其他用户发送消息。

export const newMess = (body) => async (dispatch, getState) => {
  try {
    const {activeConversation} = getState();
    if (!body.conversationId) {
      dispatch(addConversation(body.recipientId, data.message));
    } else {
       dispatch(setNewMessage(data.message, activeConversation));
    }
    sendMessage(data, body, activeConversation);
  } catch (error) {
    console.error(error);
  }
};

然后我从这里调用我的 reducer 函数。问题出在变量 activeConversation 上。因为我通过 socket.io 从 thunk 传递它,所以它导致两个用户具有相同的 activeConversation 值,这不是我想要的(我希望他们具有不同的值)。问题是我无法访问状态。我最初是从 thunk 获得状态的,但这导致用户 1 的 activeConversation 传递给用户 2,我需要从每个用户那里获取 activeConversation 值。我想知道是否有可能从我的 reducer 中获取 activeConversation 状态值而不是 thunk。

你的问题不是很清楚。但是,如果你想获取其他状态切片或者reducer中的整个状态,你可以使用Sharing data between slice reducers.

例如

import { combineReducers, createStore } from 'redux';

const SET_MESSAGE = 'SET_MESSAGE';
export const setNewMessage = (message, sender) => {
  return {
    type: SET_MESSAGE,
    payload: { message, sender: sender || null },
  };
};

function activeConversationReducer(state = 'Jim', action) {
  return state;
}
function conversationsReducer(state = [1, 2, 3], action) {
  return state;
}
function userReducer(state = { id: 8, username: 'josh', email: '' }, action) {
  return state;
}

const combinedReducer = combineReducers({
  activeConversation: activeConversationReducer,
  conversations: conversationsReducer,
  user: userReducer,
});

function crossSliceReducer(state, action) {
  switch (action.type) {
    case SET_MESSAGE: {
      console.log('entire state:', state);
      // do something with state
      return state;
    }
    default:
      return state;
  }
}

function rootReducer(state, action) {
  const intermediateState = combinedReducer(state, action);
  const finalState = crossSliceReducer(intermediateState, action);
  return finalState;
}

const store = createStore(rootReducer);
store.dispatch(setNewMessage('data', 'sender'));

执行结果:

entire state: {
  activeConversation: 'Jim',
  conversations: [ 1, 2, 3 ],
  user: { id: 8, username: 'josh', email: '' }
}