无法从React应用中的Redux存储中读取数据

时间:2020-10-15 15:23:55

标签: reactjs redux

这是我的React代码,其中使用useSelector,我试图从商店中读取一个名为currentUser的属性,但它不起作用:-

  import { useSelector } from 'react-redux';
  const currentUsr = useSelector(state => {
    console.log('state:', state);
    //state.get('currentUser');
    state.currentUser;
  });
  console.log('currentUsr', currentUsr);

如果我仅控制台打印状态,则状态如下:-

Map {size: 7, _root: ArrayMapNode, __ownerID: undefined, __hash: undefined, __altered: false}
size: 7
__altered: false
__hash: undefined
__ownerID: undefined
_root: ArrayMapNode {ownerID: OwnerID, entries: Array(7)}
__proto__: KeyedCollection

我可以使用Redux开发工具插件(请参见屏幕截图)在Redux存储中查看数据:- enter image description here

总是以未定义的形式出现。

这是我的用户信息简化程序:-

import Immutable from 'immutable';
import * as actions from '../actions/actionTypes';

const initialState = Immutable.Map({});

export const setUserInfo = (state = initialState, action) => {
  switch (action.type) {
    case actions.ADD_USER:
      return state.merge({
        uid: action.uid,
        permissions: action.permissions,
        locale: action.locale,
      });
    default:
      return state;
  }
};

我尝试了很多调试,但是仍然无法从Redux存储中读取currentUser。非常感谢您对此提供的帮助,因为我对此完全不了解。谢谢

2 个答案:

答案 0 :(得分:0)

当您使用useSelector()或useDispatch()时,它应该分别返回状态和调度动作。在上面的代码中,useSelector()中缺少return语句。

您可以用以下两种方式之一书写:

const currentUsr = useSelector(state => {
    console.log('state:', state);
    //state.get('currentUser');
    return state.currentUser;
  });

const currentUsr = useSelector(state => state.currentUser);

更新: 尝试像这样改变状态:

 case actions.ADD_USER: {
    let newState = {...state, {
        uid: action.uid,
        permissions: action.permissions,
        locale: action.locale,
      }
  }

  return state.merge(newState);
}

答案 1 :(得分:0)

我没有正确地使用Immutable JS从Redux读取数据。在Immutable中,数据以Map的形式存储,因此我应该在其get()中将键作为“ uid”发送。

此代码对我有用:-

const currentUsr = useSelector(state => state.get('currentUser'));
console.log('currentUsr uid', currentUsr.get('uid'));