简体   繁体   English

Javascript.map(…) 与 React 组件

[英]Javascript .map(…) with React Component

In my React code I have something like在我的 React 代码中,我有类似的东西

{elements.map((element) => {
   return (
      <div>
           {renderDate(element.date)}
      </div>
   )
}})}

where在哪里

const renderDate = (date: string) => {
    return (
        <div>
            <span className="date">
                {date}
            </span>
        </div>
    )
}

When I look at the UI, I see that all the elements on the page have the same date as the last date in the elements array.当我查看 UI 时,我看到页面上的所有元素的日期都与elements数组中的最后一个日期相同。 However I want to maintain each elements date and not have it been overwritten.但是我想保持每个元素的日期而不是被覆盖。 Can anyone offer suggestion?任何人都可以提供建议吗? Should I turn .map(...) into .forEach(...) ?我应该把.map(...)变成.forEach(...)吗?

Without further details I can't say for sure, but it might just be syntax.如果没有更多细节,我不能肯定地说,但它可能只是语法。 I think you have an extra closing brace ( } ) on the last line.我认为您在最后一行有一个额外的右大括号( } )。 Try this:尝试这个:

{elements.map((element, i)=> (
  <div key={i} >
    {renderDate(element.date)}
  </div>
))}

As mentioned, you also need to add a key prop.如前所述,您还需要添加一个key道具。 If the elements array is not going to be updated, causing the component to re-render, a simple index key like above will work.如果elements数组不会被更新,导致组件重新渲染,那么像上面这样的简单索引key将起作用。 Alternatively, if the dates are all unique you could use <div key={element.date}> , or another value which is unique to each item.或者,如果日期都是唯一的,您可以使用<div key={element.date}>或每个项目唯一的另一个值。

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

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