javascript - React 组件不使用“mapStateToProps”从减速器读取状态
问题描述
我正在使用 reducer 来读取状态并查看用户是否经过身份验证。我可以从其他文件中读取状态,但只有一个特定文件无法读取状态。
下面,我定义了 mapStateToProps
const mapStateToProps = state => ({
user: state.auth.user,
isAuthenticated: state.auth.isAuthenticated,
});
export default connect(mapStateToProps)(ViewJobPage);
这是组件的渲染方法
render() {
const {user, isAuthenticated} = this.props;
if(!isAuthenticated){
return <Redirect to='/'/>;
}
return(
<Card
style={{ width: 300 }}
cover={
<img
alt="example"
src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
/>
}
actions={[
<SettingOutlined key="setting" />,
<EditOutlined key="edit" />,
<EllipsisOutlined key="ellipsis" />,
]}
>
<Card.Meta
avatar={<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />}
//title={user.username}
//description={"Email: " + {user.email}}
/>
</Card>
);
}
编辑:这是我的 reducer 文件,名为“auth.js”,它将用户的状态存储为一个对象,并将 isAuthenticated 存储为布尔值
首先,我定义初始状态,然后对其进行更改,如上所述,我可以从其他文件中读取状态,因此该文件应该可以工作。还有一个额外的细节,当我第一次执行这样的代码时,它在 ViewPage 上运行,但是当我重新运行代码而不进行额外更改时,它停止读取。它可能与混合文件路径有关吗?
// frontend/src/reducers/auth.js
import {
USER_LOADING,
USER_LOADED,
AUTH_ERROR,
REGISTER_FAIL,
REGISTER_SUCCESS,
LOGIN_SUCCESS,
LOGIN_FAIL,
LOGOUT_SUCCESS,
} from '../actions/types';
const initialState = {
isLoading: false,
isAuthenticated: null,
user: null,
token: localStorage.getItem('token')
};
export default function(state = initialState, action) {
switch (action.type) {
case USER_LOADING:
return {
...state,
isLoading: true
};
case USER_LOADED:
return {
...state,
isLoading: false,
isAuthenticated: true,
user: action.payload
};
case LOGIN_SUCCESS:
localStorage.setItem('token', action.payload.token);
return {
...state,
isLoading: false,
isAuthenticated: true,
...action.payload
};
case AUTH_ERROR:
case REGISTER_FAIL:
case REGISTER_SUCCESS:
case LOGIN_FAIL:
localStorage.removeItem('token');
return {
...state,
isLoading: false,
isAuthenticated: false,
user: null,
token: null
};
case LOGOUT_SUCCESS: // added
localStorage.removeItem('token');
return {
...state,
isLoading: false,
isAuthenticated: false,
user: null,
token: null
};
default:
return state;
}
}
编辑 2:按照建议,我使用 Redux Extension 来查看状态。状态似乎是正确的。
{
type: 'USER_LOADED',
payload: {
id: 1,
username: 'david',
email: 'david@admin.com',
is_employer: true,
is_employee: false
}
}
谢谢您的帮助!
解决方案
你打connect
了两次电话。你只需要调用一次。
所以代替这个:
ViewJobPage = connect(
mapStateToProps
)(ViewJobPage);
export default connect(mapStateToProps)(ViewJobPage);
你应该这样写:
export default connect(mapStateToProps)(ViewJobPage);
推荐阅读
- objective-c - 如何在 Objective-C 中访问 Settings.bundle 中的本地化字符串?
- curl - 网页抓取 - 菜鸟
- python - 创建满足以下先决条件的 Anaconda 环境
- android - 搜索栏没有显示缓冲辅助栏,当点击搜索栏时,视频视图没有跳到点击的位置
- python - pySerial - 更新太慢
- c++ - 有没有办法将 Lua 成员变量绑定为对该变量名称的 C/C++ 函数的调用
- c# - C#,日期时间转换
- java - 在 Spring sleuth (2.1.0) 中添加一个自定义 id 的 span
- javascript - 添加带有样式的materializecss芯片-如何获得样式?
- mysql - Go: sql RowsAffected with ON DUPLICATE KEY UPDATE