【问题标题】:Redux state is filled but I get error state is nullRedux 状态已填充,但我得到错误状态为 null
【发布时间】: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;
    }
}

【问题讨论】:

标签: javascript reactjs react-redux state store


【解决方案1】:

你的 reducer 一定是这样的:

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

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

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

【讨论】:

  • reducer 是使用 Initialstate 声明的,我将编辑我的帖子并包含这个 reducer。填充用户对象的方式是通过 Cloud-functions 通过 Firebase 使用 GitHub 身份验证,因此 reducer 只将这个对象插入到状态中。
  • 该状态在您的 reducer 中称为 user,您正尝试在组件中以 userState 的形式访问它。
猜你喜欢
  • 1970-01-01
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 2017-01-19
  • 2017-10-15
  • 2018-12-25
  • 1970-01-01
  • 2019-05-25
相关资源
最近更新 更多