我正在学习Redux并且遇到了一个我在使用没有redux的React之前没有遇到的问题。我试图在我的一个组件名称loginStatus中显示我的状态。我已经设置了这个状态的reducer有一个初始状态,但每当我尝试启动应用程序时,我都会收到控制台错误:
无法读取属性' loginStatus'未定义的
这是我的代码:
组件
import React, {Component} from 'react';
import {connect} from 'react-redux';
import { bindActionCreators } from 'redux';
import * as authActions from './userAuthActions';
class App extends Component {
constructor(props) {
super(props);
}
render() {
if(typeof(this.props.userAuthReducer) !== 'undefined') {
test = this.props.userAuthReducer.loginStatus;
console.log(test)
} else {
console.log("it's undefined")
}
return (
<div className={"popup-logins " + this.props.userAuthReducer.loginStatus}>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
userAuthReducer:state.userAuthReducer
};
};
const mapDispatchToProps = (dispatch) => {
return bindActionCreators(authActions,dispatch);
};
export default connect(mapStateToProps,mapDispatchToProps)(App);
userAuthActions.js
export const loginUser = () => {
return {
type:'loginUser',
loggedIn:true
}
}
export const toggleRegLog = () => {
return {
type:'toggleRegLog'
}
}
userAuthReducer
let initialState = {
loginStatus: "not-logged-in"
, toggleRegLog: 'login'
};
const userAuthReducer = (state = initialState, action) => {
switch (action.type) {
case 'loginUser':
let newState;
if (action.loggedIn) {
Object.assign({}, state, {
loginStatus: "logged-in"
})
}
else {
Object.assign({}, state, {
loginStatus: "not-logged-in"
})
}
return newState;
break;
default:
return state;
}
}
export default userAuthReducer;
合并缩减器
import {combineReducers} from 'redux';
import userAuthReducer from './userAuthReducer';
function lastAction(state = null, action) {
return action;
}
export default combineReducers({
lastAction,userAuthReducer
});
奇怪的是,我最初得到的是一个未定义的控制台。\ n&#34;当我第一次启动应用程序然后立即获得值&#34;未登录&#34;。如果用户已登录,我需要使用它来隐藏/显示我的应用程序的某些部分。
通常情况下,如果我使用React而不使用Redux,我会一直使用这种方法而没有任何问题,但不能理解我在这里做错了什么?
由于
答案 0 :(得分:0)
你实际上并没有在reducer中为newState赋值,所以基本上你要返回undefined
,当然它没有loginStatus属性。将减速器更改为类似的东西可能会解决问题:
let initialState = {
loginStatus: "not-logged-in"
, toggleRegLog: 'login'
};
const userAuthReducer = (state = initialState, action) => {
switch (action.type) {
case 'loginUser':
let newState;
if (action.loggedIn) {
newState = Object.assign({}, state, {
loginStatus: "logged-in"
})
}
else {
newState = Object.assign({}, state, {
loginStatus: "not-logged-in"
})
}
return newState;
break;
default:
return state;
}
}
export default userAuthReducer;
Object.assign返回一个新对象,应用来自state
的数据和包含loginStatus
属性的最后一个参数,并将其传递给newState
变量,该变量最后返回开关盒。
下面的编辑可以更容易地推断出reducer中的逻辑:
let initialState = {
loginStatus: "not-logged-in"
, toggleRegLog: 'login'
};
const userAuthReducer = (state = initialState, action) => {
switch (action.type) {
case 'loginUser':
if (action.loggedIn) {
return Object.assign(state, { loginStatus: "logged-in" })
}
return Object.assign(state, { loginStatus: "not-logged-in" })
default:
return state;
}
}
export default userAuthReducer;