如何在这个项目中添加键

时间:2018-04-13 15:03:53

标签: 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';
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}我在某些方面尝试过它并没有用,我只是学习自己做出反应所以我有点困惑这里 这么多

1 个答案:

答案 0 :(得分:1)

在您的情况下,您需要为<FlatList />组件的每个子项设置密钥。通过反应原生文档推荐使用组件中定义的keyExtractor方法。

 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>

    );
 }

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