Javascript 从对象数组渲染 React 组件

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

Rendering React Components from Array of Objects

javascriptreactjs

提问by thatgibbyguy

I have some data called stations which is an array containing objects.

我有一些名为stations 的数据,它是一个包含对象的数组。

stations : [
  {call:'station one',frequency:'000'},
  {call:'station two',frequency:'001'}
]

I'd like to render a ui component for each array position. So far I can write

我想为每个数组位置渲染一个 ui 组件。到目前为止我可以写

 var stationsArr = []
 for (var i = 0; i < this.data.stations.length; i++) {
     stationsArr.push(
         <div className="station">
             {this.data}
         </div>
     )
 }

And then render

然后渲染

render(){
 return (
   {stationsArr}
 )
}

The problem is I'm getting all of the data printing out. I instead want to just show a key like {this.data.call}but that prints nothing.

问题是我正在打印所有数据。相反,我只想显示一个类似{this.data.call}但不打印任何内容的键。

How can I loop through this data and return a new UI element for each position of the array?

如何遍历此数据并为数组的每个位置返回一个新的 UI 元素?

回答by Sebastien Lorber

You can map the list of stations to ReactElements.

您可以将站点列表映射到 ReactElements。

With React >= 16, it is possible to return multiple elements from the same component without needing an extra html element wrapper. Since 16.2, there is a new syntax <>to create fragments. If this does not work or is not supported by your IDE, you can use <React.Fragment>instead. Between 16.0 and 16.2, you can use a very simple polyfillfor fragments.

使用 React >= 16,可以从同一个组件返回多个元素,而无需额外的 html 元素包装器。从 16.2 开始,有一个新的语法 <>来创建片段。如果这不起作用或您的 IDE 不支持,您可以<React.Fragment>改用。在 16.0 和 16.2 之间,您可以对片段使用非常简单的polyfill

Try the following

尝试以下

// Modern syntax >= React 16.2.0
const Test = ({stations}) => (
  <>
    {stations.map(station => (
      <div className="station" key={station.call}>{station.call}</div>
    ))}
  </>
); 

// Modern syntax < React 16.2.0
// You need to wrap in an extra element like div here

const Test = ({stations}) => (
  <div>
    {stations.map(station => (
      <div className="station" key={station.call}>{station.call}</div>
    ))}
  </div>
); 

// old syntax
var Test = React.createClass({
    render: function() {
        var stationComponents = this.props.stations.map(function(station) {
            return <div className="station" key={station.call}>{station.call}</div>;
        });
        return <div>{stationComponents}</div>;
    }
});

var stations = [
  {call:'station one',frequency:'000'},
  {call:'station two',frequency:'001'}
]; 

ReactDOM.render(
  <div>
    <Test stations={stations} />
  </div>,
  document.getElementById('container')
);

Don't forget the keyattribute!

别忘了key属性!

https://jsfiddle.net/69z2wepo/14377/

https://jsfiddle.net/69z2wepo/14377/

回答by Thomas Valadez

I have an answer that might be a bit less confusing for newbies like myself. You can just use mapwithin the components render method.

我有一个答案,对于像我这样的新手来说可能不那么令人困惑。您可以只map在组件渲染方法中使用。

render () {
   return (
       <div>
           {stations.map(station => <div> {station} </div>)} 
       </div>
   );
}

回答by Dominic

this.datapresumably contains all the data, so you would need to do something like this:

this.data大概包含所有数据,因此您需要执行以下操作:

var stations = [];
var stationData = this.data.stations;

for (var i = 0; i < stationData.length; i++) {
    stations.push(
        <div key={stationData[i].call} className="station">
            Call: {stationData[i].call}, Freq: {stationData[i].frequency}
        </div>
    )
}

render() {
  return (
    <div className="stations">{stations}</div>
  )
}

Or you can use mapand arrow functions if you're using ES6:

或者map,如果您使用的是 ES6,则可以使用和 箭头函数:

const stations = this.data.stations.map(station =>
    <div key={station.call} className="station">
      Call: {station.call}, Freq: {station.frequency}
    </div>
);

回答by Mo.

There are couple of way which can be used.

有几种方法可以使用。

const stations = [
  {call:'station one',frequency:'000'},
  {call:'station two',frequency:'001'}
];
const callList = stations.map(({call}) => call)

Solution 1

解决方案1

<p>{callList.join(', ')}</p>

Solution 2

解决方案2

<ol>    
  { callList && callList.map(item => <li>{item}</li>) }
</ol>

Edit kind-antonelli-z8372

编辑 kind-antonelli-z8372

Of course there are other ways also available.

当然也有其他方式。