为什么数据未呈现到模板中以进行React和Redux?

时间:2018-07-26 14:38:52

标签: javascript reactjs redux

我是ReactJS的新手

我的代码是:

class HomePage extends React.Component {
    constructor(props){
    super(props)
    //make this object just for testing
    this.state = {
        dataLogin : {
            age:1,
            name :'hassan',
            city : 'yaya'
         }
      }
    }

    render() {
        const { users } = this.props;
        console.log(this.props.users.items);//Line 1
        console.log(this.props.users.items.name);//Line 2
        console.log('test object state', this.state.dataLogin);//Line 4
        return (
            <div className="col-md-6 col-md-offset-3">
                <h1>Hi {users.name}!</h1><!--Line 3-->
            </div>
        );
    }
}

function mapStateToProps(state) {
    const { users } = state;
    return {
        users
    };
}

对于Reducer代码:

export function users(state = {}, action) {
  switch (action.type) {
    case 'SUCCESS':
      return {
        items: action.users
      };
    default:
      return state
  }
}

对于 LINE 1 ,它在控制台中显示数据,但是当我尝试从对象中获取 LINE 2 中的特定属性时,它会产生错误,并将数据渲染到 LINE 3 的模板。 对于 LINE 1 ,数据为:

{id: 3, name: "ahsan", email: "ahsan@gmail.com", age: 55, country: "pdf", …}

enter image description here

对于 LINE 2 错误:

Uncaught TypeError: Cannot read property 'name' of undefined
Consider adding an error boundary to your tree to customize error handling behavior.

对于第4行

enter image description here

当我访问其键(例如名称或年龄)时,它会完美呈现。

我是ReactJS的新手,并且正在关注本教程

http://jasonwatmore.com/post/2017/09/16/react-redux-user-registration-and-login-tutorial-example#users-reducer-js

谢谢。

1 个答案:

答案 0 :(得分:0)

我想你可以试试

export function users(state = {}, action) {
      switch (action.type) {
        case 'SUCCESS':
          return {
            ...state
            users: action.users
          };
        default:
          return state
      }
    }