首页 > 解决方案 > 如何呈现项目列表而不是键

问题描述

目前下面的代码渲染得很好我得到了几个在屏幕上显示文本的 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的对象作为对象的一部分。那么这可以以某种方式使用吗?

标签: javascriptreact-native

解决方案


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
    }

推荐阅读