簡體   English   中英

迭代渲染中的嵌套json對象數組(ReactJS)

[英]Iterate through a nested json object array in the render (ReactJS)

我正在嘗試使用ReactJS迭代並在我的Web應用程序上顯示JSON的某些值。

我的渲染看起來像這樣:

render() {

  const orders = 
  Object.keys(this.state.data).map((e,i) => {
   return (
     <div key = {i}>
       <div>ID: {this.state.data[e].id}</div>
       <div>Email: {this.state.data[e].email}</div>
       <div>Note: {this.state.data[e].note}</div>
       <div>{this.findValue(e)}</div>
     </div>
   )
 })

 return (
   <div>
     <div>
       {orders}
     </div>
   </div>
 );
}

現在一切都很好,直到我運行this.findValue,它在第一次迭代后立即返回,而不是返回多個div。

findValue = (e) => {
    for(let key2 in this.state.data[e].line_items) {    
        return (
          <div>
            Line item: {this.state.data[e].line_items[key2].title}
         </div>
        )
   }

我如何能夠退回每個訂單項? 提前致謝。

當您從給定給map的函數返回一些內容時,您只是返回當前元素應該映射到新數組中的內容。 當你在for..in中返回時,你將從findValue方法返回。

您也可以在line_items的鍵數組上使用map

findValue = e => {
  const { line_items } = this.state.data[e];
  return Object.keys(line_items).map(key => (
    <div key={key}>Line item: {line_items[key].title}</div>
  ));
};

暫無
暫無

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

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