react-redux存储未更新

时间:2019-10-09 09:31:15

标签: node.js reactjs react-redux

mapStatetoProps中的值显示为未定义

Index.js文件:

static initialAction() {
    return fetchUsers();
}

render() {

    const user = this.props.user;
    console.log(user);

    return (
        <div className="usersWrapper"></div>
    )
}

const mapStateToProps = state => ({
    user: state. usersR.users.users
});

UserReducer.js文件中的部分代码:

const defaultUserState = {
   users:[],
 }

const userReducer = (state = defaultUserState , action) => {
    switch(action.type){
         case actionType.USER_DATA:
            console.log("update_user_begins",action,action.payload);

            let newState={
                    users: [...state.users, ...action.payload]
                }
            state = {...state,users: newState }          

        break;
    } 

}

console.log(state);

输出如下,

action.payload的值为:

[
    { Name: 'ABC', Age: 10, Address: 'COLOMBO 02' },
    { Name: 'DEF', Age: 11, Address: 'COLOMBO 03' },
    { Name: 'wxy', Age: 45, Address: 'Nugegoda' }
]

UserReducer的返回状态是:

{ users: { users: [ [Object], [Object], [Object] ] } }

4 个答案:

答案 0 :(得分:0)

确保不要忘记将组件连接到Redux存储区

export default connect(mapStateToProps)(myComponent)

或检查mapStateToProps上的路径并确保其为正确的路径,或注销整个状态以检查该良好的路径:

 render() {
          const state= this.props.state;
           console.log(state);

        return (
           <div className="usersWrapper">
           </div>
 )
    }


    const mapStateToProps = state => ({
        **state: state**

 });

答案 1 :(得分:0)

我想,您忘记将return添加到减速器中。

const defaultUserState = {
   users:[],
 }

const userReducer = (state = defaultUserState , action) => {
    switch(action.type){
         case actionType.USER_DATA:
            console.log("update_user_begins",action,action.payload);

            let newState={
                    users: [...state.users, ...action.payload]
                }
            return {...state, users: newState } // <= here is return, not assignment.         

        break;
    } 

}

答案 2 :(得分:0)

我认为您需要从reducer返回newState,并且不要更改先前的状态 你可以做到

const userReducer = (state = defaultUserState , action) => {
switch(action.type){
     case actionType.USER_DATA:
        console.log("update_user_begins",action,action.payload);

        let newState={
                users: [...state.users, ...action.payload]
            }
        return {...state, users: action.payload }          

} 

}

希望有帮助

答案 3 :(得分:0)

情况就是我如何访问UserR的值。应该是users.users [0]。