最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot Read Property map of undefined - Stack Overflow

programmeradmin0浏览0评论

For some reason it sometimes maps through, but I get another error of not returning anything and other times it just says can't read property map of undefined. I'm trying to pile a list of users in React.

I have a ponent called UserList that is querying my database for all users and updating the state:

const UserList = React.createClass({
  getInitialState: function () {
    return {
      users: []
    }
  },
  ponentDidMount: function () {
    this.loadUsersFromServer();
  },
  loadUsersFromServer: function () {
    axios.get('/api/users').then((users) => {
      this.setState({users: users.data.users});
    });
  },
  render: function () {
    return (
      <div>

        <h1>User List</h1>

        <User
          users={this.state.users}
        />

      </div>
    );
  },
});

I'm then passing it to it's child ponent User, and that is where the error is ing into play:

const User = React.createClass({


  render: function () {
    console.log('props: ' + JSON.stringify(this.props.users));

    const users = this.props.users.map((user) => {
      return (
        <User
          key={user._id}
          username={user.username}
        />
      );
    });

    return (
      <div id="users">
        {users}
      </div>
    );
  },
});

What is interesting in the Chrome Dev tools is that for some reason I get three logs when trying to print out the this.props.users, and I'm not sure why it logs out three, but the middle one has all the users I'm looking for:

Any help would be greatly appreciated!

For some reason it sometimes maps through, but I get another error of not returning anything and other times it just says can't read property map of undefined. I'm trying to pile a list of users in React.

I have a ponent called UserList that is querying my database for all users and updating the state:

const UserList = React.createClass({
  getInitialState: function () {
    return {
      users: []
    }
  },
  ponentDidMount: function () {
    this.loadUsersFromServer();
  },
  loadUsersFromServer: function () {
    axios.get('/api/users').then((users) => {
      this.setState({users: users.data.users});
    });
  },
  render: function () {
    return (
      <div>

        <h1>User List</h1>

        <User
          users={this.state.users}
        />

      </div>
    );
  },
});

I'm then passing it to it's child ponent User, and that is where the error is ing into play:

const User = React.createClass({


  render: function () {
    console.log('props: ' + JSON.stringify(this.props.users));

    const users = this.props.users.map((user) => {
      return (
        <User
          key={user._id}
          username={user.username}
        />
      );
    });

    return (
      <div id="users">
        {users}
      </div>
    );
  },
});

What is interesting in the Chrome Dev tools is that for some reason I get three logs when trying to print out the this.props.users, and I'm not sure why it logs out three, but the middle one has all the users I'm looking for:

Any help would be greatly appreciated!

Share Improve this question asked Jan 31, 2017 at 17:27 Taylor KingTaylor King 8114 gold badges10 silver badges22 bronze badges 6
  • I'm very new to React myself, so I'm mostly following along to see other people's answers. But, I'm using the extends React.Component syntax which gives me a constructor to use for initial state. I don't have the problem of the empty array [] trying to render using that syntax. – Danny Ellis Jr. Commented Jan 31, 2017 at 17:37
  • Yeah, I mean I could try that I suppose ... I just know that's two different ways of writing the same thing, so I can't imagine that would be the issue. Or at least I somewhat hope the issue wouldn't be that ha. – Taylor King Commented Jan 31, 2017 at 17:42
  • 2 In your User class render method. You're rendering a bunch of User ponents. This is some kind of recursive self-reference that I don't really understand. In your map function do you want to return a <div /> or something rather than a <User />? – Tom Coughlin Commented Jan 31, 2017 at 17:42
  • 1 The first time your map function runs, you're creating a <User /> ponent that has 'key' and 'username' props, so the 'users' prop is undefined at that moment. – Tom Coughlin Commented Jan 31, 2017 at 17:45
  • @TomCoughlin ah ... good point. Do I even need to map it into a ponent, or could I just put it into a div? – Taylor King Commented Jan 31, 2017 at 17:45
 |  Show 1 more ment

2 Answers 2

Reset to default 1

You could try putting the users rendering logic in a method of your UserList class. Something close to this should work.

const UserList = React.createClass({
  getInitialState: function () {
    return {
      users: []
    }
  },
  ponentDidMount: function () {
    this.loadUsersFromServer();
  },
  loadUsersFromServer: function () {
    axios.get('/api/users').then((users) => {
      this.setState({users: users.data.users});
    });
  },
  renderUsers: function (users) {
    return <div>{users.map(user => <div key={user._id} username={user.username} />)}</div>
  },
  render: function () {
    return (
      <div>
        <h1>User List</h1>
        { this.renderUsers(this.state.users) }
      </div>
    );
  },
});

At some moment (second refresh) this.props.users looks undefined and the map function cannot handle it.

I rewrote the example using React.Component syntax since I never worked with the old React (before V0.13) syntax.

Check more on different syntax here.

However, this part:

const User = React.createClass({
  render: function () {
    console.log('props: ' + JSON.stringify(this.props.users));

    const users = this.props.users.map((user) => {
      return (
        <User
          key={user._id}
          username={user.username}
        />

looks strange. I think you used User inside User.

Here is how I rewrote it, with some minor modification since I haven't user axios.


class UserList extends React.Component{
  constructor(props){
    super(props);      
    this.state = { users : []  };
  }  
  ponentDidMount() {    
    this.loadUsersFromServer();    
  }
  loadUsersFromServer(){      
    this.setState({users: 
                  
                  [{
  "_id": 1,
  "username": "Nicole",
  "password": "0uTjaH",
  "_v": "7.6.9"
}, {
  "_id": 2,
  "username": "Steve",
  "password": "22l8h6a8NPU",
  "_v": "7.41"
}, {
  "_id": 3,
  "username": "Joyce",
  "password": "yA3efEc",
  "_v": "6.3"
}, {
  "_id": 4,
  "username": "Todd",
  "password": "7LsQ9aHqIfhy",
  "_v": "7.1"
}, {
  "_id": 5,
  "username": "Maria",
  "password": "uHZ5fkCi04v",
  "_v": "9.31"
}]
                  
                  
                  });
  }
  
  render(){    
    return (
      <div>
        <h1>User List </h1>
        <User users={this.state.users}   />
      </div> 
    );
  }
};

class User extends React.Component{
  constructor(props){
    super(props);
  }
  
  render(){
    console.log(typeof(this.props.users));
    //console.log(this.props.users);

    //const user = JSON.stringify(this.props.users);
    
    const userList = this.props.users.map((user) => {
      return (
        <div>
          <span>key={user._id}</span>
          <span>username={user.username}</span>
        </div>
      );
    });

    return (
      <div id="users">
        {userList}
      </div>
    );
  }
  
}

ReactDOM.render(<UserList /> , document.getElementById('root') );
span {padding: 3px}
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

发布评论

评论列表(0)

  1. 暂无评论