排序日期抛出异常 TypeError: data.createdAt.sort is not a function
。我想先在我的 React 应用中排序并显示最新记录。
{
displayWinner.map(data => (
<div key={data.id}className="oldwinner">
<div className="winnerIcon">
<img src="/images/trophy1.png"></img>
<span key={data.winner} className="winner name">{data.winner}</span>
<span key={data.createdAt} className="winner date">{moment(data.createdAt.sort((a, b) => b - a)).format('DD-MMM-YYYY')}</span>
</div>
</div>
))
}
https://codesandbox.io/s/zen-edison-l4shu?file=/src/styles.css
答案 0 :(得分:1)
您需要对数据进行排序然后映射它,sort((a, b) => moment(b.createdAt) - moment(a.createdAt))
。取每个元素,将createdAt
属性转换为momentjs DateTime对象进行数值比较
{displayWinner
.sort((a, b) => moment(b.createdAt) - moment(a.createdAt))
.map((data,) => (
<div key={data.createdAt} className="oldwinner">
<div className="winnerIcon">
<img key="data" src="/images/trophy1.png"></img>
<span key={data.winner} className="winner name">
{data.winner}
</span>
<span key={data.createdAt} className="winner date">
{moment(data.createdAt).format("DD-MMM-YYYY")}
</span>
</div>
</div>
))}
答案 1 :(得分:0)
排序应该在映射值之前完成
{
displayWinner.sort((a, b) => moment(b.createdAt).format('DD-MMM-YYYY') - moment(a.createdAt).format('DD-MMM-YYYY')).map(data => (
<div key={data.id}className="oldwinner">
<div className="winnerIcon">
<img src="/images/trophy1.png"></img>
<span key={data.winner} className="winner name">{data.winner}</span>
<span key={data.createdAt} className="winner date">{moment(data.createdAt).format('DD-MMM-YYYY')}</span>
</div>
</div>
))
}
答案 2 :(得分:0)
至少有 2 种情况您可以获得此 TypeError: x.sort is not a function
。当您尝试在 sort
或 string
上调用 Object
时。在您的情况下,您首先需要对值进行排序然后映射。
{
displayWinner.sort((a, b) => b - a).map(data => (
<div key={data.id} className="oldwinner">
<div className="winnerIcon">
<img src="/images/trophy1.png"></img>
<span key={data.winner} className="winner name">{data.winner}</span>
<span key={data.createdAt} className="winner date">
{ moment(data.createdAt.format('DD-MMM-YYYY') }
</span>
</div>
</div>
))
}