Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

javascript - Loop through simple array of objects in React

I am not using JSX. Is this a problem? Is this considered bad practice?

var links = [
  { endpoint: '/america' },
  { endpoint: '/canada' },
  { endpoint: '/norway' },
  { endpoint: '/bahamas' }
];

class Navigation extends React.Component {
  render() {
    return (
      <div className="navigation">
        <ul>
          const listItems = links.map((link) =>
            <li key={link.endpoint}>{link.endpoint}</li> 
          );
        </ul>
      </div>
    );
}

Based on the basic list component section of the react docs, it seems like I should be able to print the contents of an array, the way I'm doing it inside my <ul></ul>

https://facebook.github.io/react/docs/lists-and-keys.html#basic-list-component

Is the problem that I am using an array of objects? The docs are using a simple array. I'd appreciate a push into the right direction.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The issue is that your syntax is invalid, you should have something like this :

var links = [
  { endpoint: '/america' },
  { endpoint: '/canada' },
  { endpoint: '/norway' },
  { endpoint: '/bahamas' }
];

class Navigation extends React.Component {
  render() {
    const listItems = links.map((link) =>
        <li key={link.endpoint}>{link.endpoint}</li> 
    );
    return (
      <div className="navigation">
        <ul>
          {listItems}
        </ul>
      </div>
    );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...