【问题标题】:How to get a React Redux state value from the reducer?如何从 reducer 获取 React Redux 状态值?
【发布时间】:2021-10-28 18:36:09
【问题描述】:

在 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。因为我从 thunk 通过 socket.io 传递它,所以这导致两个用户具有相同的 activeConversation 值,这不是我想要的(我希望它们具有不同的值)。问题是我无法访问该状态。我最初从 thunk 获得了状态,但这导致来自用户 1 的 activeConversation 被传递给用户 2,我需要从每个用户那里获取 activeConversation 值。我想知道是否有可能从我的减速器而不是 thunk 中获取 activeConversation 状态值。

【问题讨论】:

    标签: javascript reactjs redux redux-thunk redux-reducers


    【解决方案1】:

    你的问题不是很清楚。但是,如果你想在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: '' }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-08
      • 2017-04-02
      • 2017-12-31
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      • 2019-04-01
      • 2021-01-24
      • 2019-05-24
      相关资源
      最近更新 更多