Reactjs 如何在此项目中添加键

Reactjs 如何在此项目中添加键,reactjs,react-native,Reactjs,React Native,我正在使用react o nexpo xde,当我运行这个项目时,我得到一个警告,因为我的列表没有键,我想知道在哪里以及如何分配它们,这是我的代码 import React, { Component } from 'react'; import { StyleSheet, Text, View,AppRegistry,Image,ActivityIndicator, FlatList,Navigator,TouchableHighlight, } from 'react-native'; imp

我正在使用react o nexpo xde,当我运行这个项目时,我得到一个警告,因为我的列表没有键,我想知道在哪里以及如何分配它们,这是我的代码

import React, { Component } from 'react';
import { StyleSheet, Text, View,AppRegistry,Image,ActivityIndicator, FlatList,Navigator,TouchableHighlight, } from 'react-native';
import { StackNavigator } from 'react-navigation';

  class Lista extends Component {
    static navigationOptions = {
      title: 'Lista',
    }
    constructor(props) {
      super(props);
      this.state = {
        data:[]
      };

    }
    load = async ()=>{
      try{
        let resp = await fetch('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=fd829ddc49214efb935920463668608d')
        let json = await resp.json()
        this.setState({data:json.articles})
      } catch (err) { console.log(err) }
    }

    componentDidMount(){this.load()}
    render() {
      return (
        <View style={{ flex: 1}}>
          <View style={{ flex:1,backgroundColor:'gray'}}>
            <FlatList
              data={this.state.data}
              renderItem={({item}) => (
                <TouchableHighlight onPress={() => this.props.navigation.navigate('Details', {item})}>
                  <View style={{ height:100,margin:15,backgroundColor:'skyblue', padding: 10, flexDirection: 'row'}}>
                    {item.urlToImage !== null &&
                      <Image source={{uri:item.urlToImage}} style={{width: 90, height: 80 }}/>
                    }
                    <View style={{ flex: 1 }}>
                      <Text style={{ textAlign: 'center',fontWeight: 'bold', fontSize: 18, color: 'white', flex:1, margin:10}}>{item.title}</Text>
                      <Text style={{ textAlign: 'right',fontWeight: 'bold', fontSize: 11, color: 'white'}}>{item.publishedAt}</Text>
                    </View>
                  </View>
                </TouchableHighlight>
              )}
            />
          </View>
        </View>
      );
    }
  }
  class DetailsScreen extends React.Component {
    static navigationOptions = ({ navigation }) => {
      const { item } = navigation.state;
      return {
        title: item ? item.date : 'Details Screen',
      }
    };

    render() {
      return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <Image source={{uri:this.props.navigation.state.params.item.urlToImage}} style={{width: 90, height: 80 }}/>
          <Text>{this.props.navigation.state.params.item.title}</Text>
          <Text>{this.props.navigation.state.params.item.publishedAt}</Text>
        </View>
      );
    }
  }

  const RootStack = StackNavigator(
    {
      Lista: {
        screen: Lista,
      },
      Details: {
        screen: DetailsScreen,
      },
    },
    {
      initialRouteName: 'Lista',
    }
  );
  const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
    },
  });

  export default class App extends React.Component {
    render() {
      return <RootStack />;
    }
  }
我知道它必须是这样的,key={i}但是我已经尝试了一些方法,但它不起作用,我只是在学习自己的反应,所以我在这里有点困惑
在您的情况下,您需要为组件的每个子级设置密钥。由react native docs推荐使用组件中定义的方法

 keyExtractor = (item, index) => index

 render() {

 return (
  <View style={{ flex: 1}}>
    <View style={{ flex:1,backgroundColor:'gray'}}>
     <FlatList
      data={this.state.data}
      keyExtractor={this.keyExtractor}
      renderItem={({item}) => (

      <TouchableHighlight onPress={() => this.props.navigation.navigate('Details', {item})}>
    <View style={{ height:100,margin:15,backgroundColor:'skyblue', padding: 10, flexDirection: 'row'}}>
      {item.urlToImage !== null &&
        <Image source={{uri:item.urlToImage}} style={{width: 90, height: 80 }}/>
      }
      <View style={{ flex: 1 }}>
        <Text style= {{ textAlign: 'center',fontWeight: 'bold', fontSize: 18, color: 'white', flex:1, margin:10}}>{item.title}</Text>
        <Text style= {{ textAlign: 'right',fontWeight: 'bold', fontSize: 11, color: 'white'}}>{item.publishedAt}</Text>
       </View>
      </View>
     </TouchableHighlight>
      )}
    />
    </View>
  </View>

    );
 }

我只将元素的索引设置为键,但您可以随意设置,但请确保它是唯一的。但是使用索引是不好的做法,不安全。

我的列表没有键:哪个列表会引发此错误?您试图修复什么?使用索引作为密钥是不安全的。添加、删除或重新排序项目将导致错误行为。您应该只对永远不会改变的静态数据执行此操作。@trixn,我知道,我只是以索引为例来澄清我的答案。我编辑它来写你的推荐,谢谢。