簡體   English   中英

過濾2個數組以在React / JSX中呈現值

[英]Filtering 2 arrays to render a value in React/JSX

我正在嘗試在React中渲染項目列表。 我正在遍歷具有所有可能的值interests的列表,並將其與具有這些值的子集的另一個列表event.Interests 我比較_id與保存在子表S _id的完整列表秒。

{console.log(e === interest._id)}返回true 5次,如果interest.Label被記錄,將返回每個值的名稱。

但是,它們都沒有在UI中呈現。

event && interests && interests.forEach(interest => (
  event.Interests.filter((e, i) => {
    {console.log(e === interest._id)}
    if (e === interest._id) {
      return <div key={i} className={classNames(classes.categoryContainer, classes.leftPadding)}>
        <div className={classes.categoryWrapLower}>
          <p>{interest.Label}</p>
        </div>
      </div>
    }
  })
))

我究竟做錯了什么?

UPDATE

根據samanime的建議,我將forEach更改為一張map ,並且奇怪的是,它工作得很好。

      event && interests && interests.map(interest => (
        event.Interests.map((e, i) => {
          {console.log(e === interest._id)}
          if (e === interest._id) {
            return <div key={i} className={classNames(classes.categoryContainer, classes.leftPadding)}>
              <div className={classes.categoryWrapLower}>
                <p>{interest.Label}</p>
              </div>
            </div>
          }
        })
      ))

將您的forEach()更改為map()

forEach()函數沒有返回值,因此,如果從那里返回任何內容,它只會被丟棄。

map()函數將收集所有返回的值(如果不返回任何值,則包括undefined值),並將它們作為數組返回。

對於您的情況,您需要使用map() ,然后在地圖后添加.filter(Boolean) ,以刪除不返回任何內容的情況下所有undefined的內容。

event && interests && interests.map(interest => /* your code */).filter(Boolean)

暫無
暫無

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

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