Javascript 如何在 JSX 中使用 map 嵌套循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47402365/
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:50:01  来源:igfitidea点击:

How to have nested loops with map in JSX?

javascriptreactjsjsx

提问by vmarquet

I can't achieve to have two nested map:

我无法实现有两个嵌套map

render() {
    return (
      <table className="table">
        <tbody>
          {Object.keys(this.state.templates).map(function(template_name) {
            return (
              <tr key={template_name}><td><b>Template: {template_name}</b></td></tr>

              {this.state.templates[template_name].items.map(function(item) {
                return (
                  <tr key={item.id}><td>{item.id}</td></tr>
                )
              })}
            )
          })}
        </tbody>
      </table>
    )
  }

This gives a SyntaxError: unknown: Unexpected token.

这给出了一个SyntaxError: unknown: Unexpected token.

How do you nest mapcalls in JSX?

你如何map在 JSX 中嵌套调用?

回答by Sagiv b.g

You need to wrap it inside an element.

您需要将它包装在一个元素中。

Something like this (I've added an extra trdue to the rules of tables elements):

像这样的东西(tr由于表格元素的规则,我添加了一个额外的东西):

  render() {
    return (
      <table className="table">
        <tbody>
          {Object.keys(templates).map(function (template_name) {
            return (
              <tr key={template_name}>
                <tr>
                  <td>
                    <b>Template: {template_name}</b>
                  </td>
                </tr>
                {templates[template_name].items.map(function (item) {
                  return (
                    <tr key={item.id}>
                      <td>{item}</td>
                    </tr>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
      </table>
    );
  }
}

Running Example (without a table):

运行示例(没有表格):

const templates = {
  template1: {
    items: [1, 2]
  },
  template2: {
    items: [2, 3, 4]
  },
};

const App = () => (
  <div>
    {
      Object.keys(templates).map(template_name => {
        return (
          <div>
            <div>{template_name}</div>
            {
              templates[template_name].items.map(item => {
                return(<div>{item}</div>)
              })
            }
          </div>
        )
      })
    }
  </div>
);
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

回答by rainkowla

I think the problem is that the return type should be an array but not an object in React16. You could try like this below:

我认为问题在于 React16 中的返回类型应该是数组而不是对象。你可以像下面这样尝试:

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      templates: {
        foo: {
          items: [
            {id: 0},{id:1}
          ]
        },
        bar: {
          items: [
            {id: 2},{id:3}
          ]
        }
      }
    }
  }
  
  renderTemplate = (template, name) => {
    let data = []
    data = template.items
    data.unshift({ name: name })
    return data.map((item, index) => <tr key={index}><td>{item.name ? item.name : item.id}</td></tr>)
  }
  
  render() {
    return (
      <table>
        <tbody>
          {Object.keys(this.state.templates).map(name => {
            return this.renderTemplate(this.state.templates[name], name)
          })}
        </tbody>
      </table>
    )
  }
}



ReactDOM.render(<App />, document.getElementById('root'))
td {
  color: white;
  padding: 0 20px;
  background: grey;
}
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.1.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.1.1/umd/react-dom.production.min.js"></script>

回答by Lliam Scholtz

I struggled for a while to get my nested map function to work only to discover that whatyou returnis critical. Make sure you are returning the second map itself and not just the final expected output:

我努力让我的嵌套 map 函数工作了一段时间,却发现whatreturn很重要。确保您返回的是第二张地图本身,而不仅仅是最终的预期输出:

let { categories } = data;

categories = categories.map(category =>
    category.subcategories.map((subcategory, i) => <h2 key={i}>{subcategory.name}</h2>)
);

return (
    <div className="category-container">
        <div>{categories}</div>
    </div>
);