【发布时间】:2018-11-04 15:43:22
【问题描述】:
我目前正在开展一个涉及已登录用户的项目。在我的 redux 状态下,我有一个用户,它是一个不为空的对象。但是当我尝试从这个用户对象中获取一个角色时,我突然收到一个错误“状态为空”
this.props.userState.user
返回一个具有角色属性的用户对象。
this.props.userState.user.role
抛出错误“TypeError: this.props.userState.user is null”
编辑:以下是整个文件中的所有代码。
class ResultsMain extends Component {
componentDidMount() {
firebase.auth().onAuthStateChanged(user => {
if (user)
getUser(user.email).then(foundUser => {
console.log('User found:', foundUser);
this.props.doSetUser(foundUser);
}).catch((err) => {
console.log(err)
this.props.history.push('/');
});
});
}
render() {
console.log("THE PROPS", this.props.userState.user)
if (this.props.userState.role === "teacher") return <TeacherSearchPage/>
else return <Results />
//else return <div> </div>
}
}
function mapStateToProps(state) {
return {
userState: state.userState,
}
}
function mapDispatchToProps(dispatch) {
return {
doSetUser: user => dispatch(userActions.setUser(user)),
}
}
export const resultsMainPage = ReactRedux.connect(mapStateToProps, mapDispatchToProps)(ResultsMain);
减速器:
const initialState = {
user: null,
finished: false,
}
function copyAndUpdateObj(copiedObject, update) {
return Object.assign({}, copiedObject, update);
}
export default function userReducer(state = initialState, action) {
switch (action.type) {
case INSERT_USER:
return {...state, user: action.userInformation};
case SET_USER: {
let changes = {
user: action.user
}
return copyAndUpdateObj(state, changes);
}
default:
return state;
}
}
【问题讨论】:
-
您需要先提供Minimal, Complete, and Verifiable example,然后才能有人帮助您
-
用户初始状态为空?
-
你能分享一些代码库吗?
标签: javascript reactjs react-redux state store