You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从React Redux的reducer中获取指定state的属性值?

结论先行

你不需要也不能跨用户从reducer取值,这个问题的核心是逻辑错误:你把发送方本地的activeConversation通过socket传给了接收方,和你从thunk还是reducer取值没有关系,每个用户的Redux状态都是独立保存在自己客户端的,不存在跨用户取值的可能。

问题根因

你当前的逻辑是:

  • 发送方在自己的thunk里取了本地的activeConversation,塞进socket消息里发给接收方
  • 接收方直接用了发送方传过来的这个值,自然就和发送方的activeConversation完全一致
  • 接收方自己的activeConversation本身就存在自己本地的Redux里,根本不需要你从发送方传过去

修复方案

  1. 修改socket发送逻辑,去掉sendMessage里的activeConversation参数,这个值是发送方本地状态,对接收方没有意义,你只需要传消息内容、会话ID、发送方ID三个核心字段即可。
  2. 修改setNewMessage action的传参,不需要外部传入activeConversation,reducer本身就可以访问当前用户的全部state,直接在reducer内部取自己的activeConversation即可:
// 会话模块reducer示例
const initialState = {
  activeConversation: "",
  conversations: []
}
const conversationReducer = (state = initialState, action) => {
  switch(action.type) {
    case 'SET_NEW_MESSAGE':
      // 直接在reducer内部取当前用户自己的activeConversation
      const currentActiveChat = state.activeConversation
      const newMsg = action.payload.message
      // 后续按你的业务逻辑处理:判断新消息所属会话是否等于当前激活会话,再更新会话列表/未读计数
      return {
        // 你的状态更新逻辑
      }
    default:
      return state
  }
}
  1. 对应修改thunk代码,删除多余的传参:
export const newMess = (body) => async (dispatch, getState) => {
  try {
    const {activeConversation} = getState();
    // 注意你原代码里的data没有定义,自行补全取值逻辑
    const message = data.message;
    if (!body.conversationId) {
      dispatch(addConversation(body.recipientId, message));
    } else {
       // 仅传消息即可,activeConversation reducer自己会取
       dispatch(setNewMessage(message));
    }
    // 发socket时删除activeConversation参数
    sendMessage(data, body);
  } catch (error) {
    console.error(error);
  }
};

内容的提问来源于stack exchange,提问作者Josh Susa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 17:18:01