javascript - 如何呈现项目列表而不是键
问题描述
目前下面的代码渲染得很好我得到了几个在屏幕上显示文本的 TEXT 组件
我也收到警告,但上面写着
each child in a list should have a unique "key" prop
renderAlertItem = (alerts) => {
arr = []
for (var x = 0; x < alerts.length-1; x++){ //the last item in the list is the add alert button so we can ignore it
arr.push(
<Text style={{color: colors.whiteText}} >
Settings for the {alerts[x].alertname} alert
</Text>
)
}
return arr
}
render() {
const alerts=this.props.alerts
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center',}}>
{this.renderAlertItem(alerts)}
</View>
);
}
解决这个问题的最佳方法是什么?
这样做会产生错误,因为代码现在返回对象列表,而不是<Text>
像以前那样返回组件列表。
arr.push({key:x,item:
<Text style={{color: colors.whiteText}} >
Settings for the {alerts[x].alertname} alert
</Text>
})
注意:这this.props.alerts
是一个与此类似的对象列表,[{key:1, alertname:name, alerttype:type, setting:30}]
它已经拥有自己key
的对象作为对象的一部分。那么这可以以某种方式使用吗?
解决方案
renderAlertItem = (alerts) => {
arr = []
for (var x = 0; x < alerts.length-1; x++){ //the last item in the list is the add alert button so we can ignore it
arr.push(
<Text style={{color: colors.whiteText}} key={x}>
Settings for the {alerts[x].alertname} alert
</Text>
)
}
return arr
}
推荐阅读
- multipart - 通过 aiohttp 发送多部分请求
- http - 如何在 Rust 中发出简单的 POST 请求?
- excel - 将 SourceData 转换为 Range
- html - 内联 SVG 中的响应式图像
- python - 获取 flake8 返回一个非零代码: 1 在 docker
- python-3.x - 如何使用来自多列的变量过滤来自 sqlite 表的行数据?
- python - Dijkstra python库将值传递给Graph中的add_edge
- java - Dockerfile 中的 Maven + Java 应用程序
- c# - 如何在 api mvc project net core 3.1 中向控制器添加动作
- c# - C# MVVM - 共享对象 - NotifyOfPropertyChange