Redux 状态已填充但我得到错误状态为空

Redux state is filled but I get error state is null

我目前正在从事一个涉及登录用户的项目。在我的 redux 状态下,我有一个用户,它是一个不为空的对象。但是当我试图从这个用户对象中获取一个角色时,我突然得到一个错误 "state is null"

this.props.userState.user 

returns 具有角色属性的用户对象。

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;
    }
}

你的减速器必须是这样的:

function reducer(state = initialState, action) {...}

无论this.props.userState的值是什么,都来自你一开始对initialState的定义。请确保在您的应用程序中定义 initialState 对象。

仔细检查您是否在初始状态下定义了 userState.user