javascript - 如何呈现项目列表而不是键

标签 javascript react-native

目前下面的代码呈现得很好 我有几个 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
    }

关于javascript - 如何呈现项目列表而不是键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57193874/

相关文章:

javascript - 关于 Vue 和 Javascript 的简单问题

javascript - 更改 anchor 处滚动条的颜色?

iOS ReactNative : Text not wrapping and displaying off-screen

ios - react native 禁用自动旋转

javascript - 如何防止重复提交 <a href>

javascript - 在 v-for 循环中调用不同的 onClick 函数

javascript - 将 RxJS 与 filter(Boolean) 一起用于查询?

javascript - react 原生 + react 原生路由器通量 : How to apply hideNavBar to only one <Scene/>?

带有 ColdFusion 组件的 React-native axios

javascript - React Native项目中的Git和esformatter的使用