Javascript 循环遍历 React 中的简单对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45857698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:14:53  来源:igfitidea点击:

Loop through simple array of objects in React

javascriptreactjs

提问by bruh

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

我没有使用 JSX。这是一个问题吗?这被认为是不好的做法吗?

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>

基于react docs的基本列表组件部分,我似乎应该能够打印数组的内容,就像我在我的 <ul></ul>

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

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.

是我使用对象数组的问题吗?文档使用了一个简单的数组。我很感激朝着正确的方向前进。

回答by Daniel Andrei

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>
    );
}

回答by Nocebo

You should be able to do something like this:

你应该能够做这样的事情:

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