【发布时间】:2020-10-15 15:23:55
【问题描述】:
这是我使用 useSelector 的 React 代码,我试图从商店中读取一个名为 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 存储中的数据(参考屏幕截图):-
它总是以未定义的形式出现。
这是我的用户信息缩减器:-
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。我非常感谢您对此的帮助,因为我完全被它阻止了。谢谢
【问题讨论】:
-
你没有返回
state.currentUser。你试过return state.currentUser;吗? -
对不起,它不工作。我过去曾与 Redux 合作过,但从未像这样被阻止。如果您看到 redux 开发工具的屏幕截图,那么使用 state.currentUser 从中获取数据非常容易。不知道在哪里检查。仅供参考,从 './userInfoReducer' 导入 { setUserInfo as currentUser }; const appReducer = combineReducers({ authReducer, currentUser })