简体   繁体   English

如何在 React 中循环对象?

[英]How to loop an object in React?

New to React and trying to loop Object attributes but React complains about Objects not being valid React children, can someone please give me some advice on how to resolve this problem? React 新手并尝试循环 Object 属性,但 React 抱怨 Objects 不是有效的 React 子项,有人可以给我一些关于如何解决这个问题的建议吗? I've added createFragment but not completely sure where this needs to go or what approach I should take?我添加了 createFragment 但不完全确定这需要去哪里或我应该采取什么方法?

JS JS

var tifs = {1: 'Joe', 2: 'Jane'};
var tifOptions = Object.keys(tifs).forEach(function(key) {
    return <option value={key}>{tifs[key]}</option>
});

Render function渲染功能

render() {
        const model = this.props.model;

        let tifOptions = {};

        if(model.get('tifs')) {
            tifOptions = Object.keys(this.props.model.get('tifs')).forEach(function(key) {
                return <option value={key}>{this.props.model.get('tifs')[key]}</option>
            });
        }

        return (
            <div class={cellClasses}>

                    <div class="grid__col-5 text--center grid__col--bleed">
                        <h5 class="flush text--uppercase">TIF</h5>
                        <select id="tif" name="tif" onChange={this.handleChange}>
                            {tifOptions}
                        </select>
                    </div>

            </div>
        );
    }

Error in console控制台错误

If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object)

The problem is the way you're using forEach() , as it will always return undefined .问题在于您使用forEach()的方式,因为它总是会返回undefined You're probably looking for the map() method, which returns a new array:您可能正在寻找map()方法,它返回一个新数组:

var tifOptions = Object.keys(tifs).map(function(key) {
    return <option value={key}>{tifs[key]}</option>
});

If you still want to use forEach() , you'd have to do something like this:如果您仍想使用forEach() ,则必须执行以下操作:

var tifOptions = [];

Object.keys(tifs).forEach(function(key) {
    tifOptions.push(<option value={key}>{tifs[key]}</option>);
});

Update:更新:

If you're writing ES6, you can accomplish the same thing a bit neater using an arrow function :如果你正在编写 ES6,你可以使用箭头函数更简洁地完成同样的事情:

const tifOptions = Object.keys(tifs).map(key => 
    <option value={key}>{tifs[key]}</option>
)

Here's a fiddle showing all options mentioned above: https://jsfiddle.net/fs7sagep/这是一个显示上述所有选项的小提琴: https ://jsfiddle.net/fs7sagep/

You can use it in a more compact way as:您可以以更紧凑的方式使用它:

const tifs = {1: 'Joe', 2: 'Jane'};
...

return (
   <select id="tif" name="tif" onChange={this.handleChange}>  
      { Object.entries(tifs).map((t,k) => <option key={k} value={t[0]}>{t[1]}</option>) }          
   </select>
)

And another slightly different flavour:还有另一种略有不同的味道:

 Object.entries(tifs).map(([key,value],i) => <option key={i} value={key}>{value}</option>)  

When I use Object.entries with map , I use Array Destructuring like the following and just call them directly.当我将Object.entriesmap一起使用时,我使用如下所示的数组解构并直接调用它们。

Object.entries(tifs).map(([key, value]) => (
    <div key={key}>{value}</div>
));

you could also just have a return div like the one below and use the built in template literals of Javascript :你也可以有一个像下面这样的返回 div 并使用 Javascript 的内置模板文字:

const tifs = {1: 'Joe', 2: 'Jane'};

return(

        <div>
            {Object.keys(tifOptions).map((key)=>(
                <p>{paragraphs[`${key}`]}</p>
            ))}
        </div>
    )
const tifOptions = [];

for (const [key, value] of Object.entries(tifs)) {
    tifOptions.push(<option value={key} key={key}>{value}</option>);
}

return (
   <select id="tif" name="tif" onChange={this.handleChange}>  
      { tifOptions }          
   </select>
)

You can use map function您可以使用map功能

{Object.keys(tifs).map(key => (
    <option value={key}>{tifs[key]}</option>
))}
{
   Object.entries(tifOptions).map(([key, value], index) =>
       console.log("Key" + Key + "::>" + "Value" + value);
)}

I highly suggest you to use an array instead of an object if you're doing react itteration, this is a syntax I use it ofen.如果你正在做反应迭代,我强烈建议你使用数组而不是对象,这是我经常使用的语法。

const rooms = this.state.array.map((e, i) =>(<div key={i}>{e}</div>))

To use the element, just place {rooms} in your jsx.要使用该元素,只需将{rooms}放在您的 jsx 中。

Where e=elements of the arrays and i=index of the element.其中 e = 数组的元素, i = 元素的索引。 Read more here . 在这里阅读更多。 If your looking for itteration, this is the way to do it.如果您正在寻找迭代,这就是这样做的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM