如何使用React.js在JSX中遍历对象

问题描述:

所以我有一个React.js组件,我想遍历导入的一个对象以向其中添加HTML选项.这是我尝试过的方法,既丑陋又不起作用:

So I have a React.js component, and I want to loop through an object I import to add HTML options to it. Here is what I tried, which is both ugly and does not work:

import React from 'react';
import AccountTypes from '../data/AccountType';

const AccountTypeSelect = (props) => {  
  return (
    <select id={props.id} className = {props.classString} style={props.styleObject}>
        <option value="nothingSelected" defaultValue>--Select--</option>
        {
            $.each(AccountTypes, function(index) {
                <option val={this.id}>this.name</option>
            })
        }
    </select>
  );
};

export default AccountTypeSelect;

我从上面的代码在控制台中收到此错误:

I received this error in the console from the above code:

invariant.js?4599:38-未捕获的不变变量:对象作为React子对象无效(找到:具有键{id,name,enabled,additionalInfo}的对象).如果您打算渲染孩子的集合,请改用数组,或使用React附加组件中的createFragment(object)包装对象.检查AccountTypeSelect的渲染方法.

invariant.js?4599:38 - Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {id, name, enabled, additionalInfo}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of AccountTypeSelect.

我真的需要将每个对象转换为数组还是用createFragment包裹起来以使用它吗?这种情况下的最佳做法是什么?

Do I really need to convert each object into an array or wrap it with createFragment to use it? What is the best practice for this case?

使用map代替$.each:

{AccountTypes.map(function(a) {
     return (
         <option key={a.id} val={a.id}>{a.name}</option>
     );
 })}