簡體   English   中英

從對象數組渲染 React 組件

[英]Rendering React Components from Array of Objects

我有一些名為stations 的數據,它是一個包含對象的數組。

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

我想為每個數組位置渲染一個 ui 組件。 到目前為止我可以寫

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

然后渲染

render(){
 return (
   {stationsArr}
 )
}

問題是我正在打印所有數據。 我只想顯示一個像{this.data.call}這樣的鍵,但它什么也不打印。

如何遍歷此數據並為數組的每個位置返回一個新的 UI 元素?

您可以將站點列表映射到 ReactElements。

使用 React >= 16,可以從同一個組件返回多個元素,而無需額外的 html 元素包裝器。 從 16.2 開始,有一個新的語法 <>來創建片段。 如果這不起作用或您的 IDE 不支持,您可以使用<React.Fragment>代替。 在 16.0 和 16.2 之間,您可以對片段使用非常簡單的polyfill

嘗試以下

// 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')
);

不要忘記key屬性!

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

我有一個答案,對於像我這樣的新手來說可能不那么令人困惑。 您可以只在組件渲染方法中使用map

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

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

或者,如果您使用 ES6,則可以使用map和箭頭函數:

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

有幾種方法可以使用。

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

解決方案1

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

解決方案2

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

編輯 kind-antonelli-z8372

當然也有其他方式。

這很可能是實現您正在尋找的東西的最簡單方法。

為了在這個實例中使用這個map函數,我們必須傳遞一個currentValue (總是必需的)參數,以及一個index (可選)參數。 在下面的例子中, station是我們的currentValuex是我們的index

station表示數組中對象在迭代時的當前值。 x自動遞增; 每次映射一個新對象時增加一。

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

Thomas Valadez 的回答是,雖然它提供了從對象數組渲染組件的最佳/最簡單的方法,但它未能正確解決在此過程中分配鍵的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM