【问题标题】:Why can't I display my items in Flatlist?为什么我不能在 Flatlist 中显示我的项目?
【发布时间】:2018-12-07 00:41:37
【问题描述】:

我目前正在尝试学习 React-Native atm,但在我的 FlatList 中显示我的项目时遇到了一些问题。

下面是我的代码

import React from 'react';
import { FlatList, ActivityIndicator, Text, View  } from 'react-native';

export default class FetchExample extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      isLoading: true,
      dataSource: []
    }
}

  componentDidMount(){

    return fetch('https://api.coindesk.com/v1/bpi/currentprice.json')
           .then((res) => res.json())
           .then((resJson) => {
           console.log('Here are the stuff', resJson.bpi)
           this.setState({
              isLoading: false,
              dataSource: resJson.bpi,
             })
           })
// catch any potential errors here
    .catch((error) =>{
      console.log(error)
    })
  }

  render(){
if(this.state.isLoading){
  return(
    <View style={{flex: 1, padding: 20}}>
      <ActivityIndicator />
    </View>
  );
}
return(
  <View style={{flex: 0.5, padding: 20}}>
    <Text>{console.log(this.state.dataSource)}</Text>
    <Text>Here's some testing text</Text>
    <Text>{console.log("This is in this.state.dataSource", this.state.dataSource)}</Text>
    {/* <FlatList 
      data= {this.state.dataSource}
      renderItem = {({item}) => <Text>{console.log(item)}</Text>} 
      /> */}
  </View>
)
  }
}

每当我取消注释 FlatList 时,模拟器都会向我发送一条错误消息,提示“不变违规:试图获取超出范围索引 NaN 的帧”

我做错了什么? Atm 我只是想查看 item 中的内容并了解如何使用 Flatlist

【问题讨论】:

  • 为什么要把console.log放在Text里面?
  • 如果你想放console.log,你应该把它放在return之前
  • @liupluto 它暂时在那里供我查看项目中的内容。但即使我这样做 {item} 我仍然得到一个错误
  • @john doe 你能试试item.USD.code 看看输出是什么吗?
  • @AravindS 是的,只是这样做了,但仍然遇到问题中提到的相同错误

标签: json react-native


【解决方案1】:

我是怎么做的

 <FlatList
          data={[this.state.dataSource]}
          renderItem={({ item }) => this._renderListItem(item)}
        />

这里是 _renderListItem()

 _renderListItem(item){
    console.log(item)
      return(
        <View>
          <View style={{flexDirection:'row',width:'100%',backgroundColor:'red'}}>
          <Text>{item.USD.code}</Text>
          <Text>{item.USD.symbol}</Text>
          <Text>{item.USD.description}</Text>
          </View>
        </View>
        )
    }

这里是博览会链接click here you get the idea 如果您有任何问题,请问我...

【讨论】:

  • 这很有魅力,而且很容易理解。谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-05-16
  • 2021-07-22
  • 1970-01-01
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-04
相关资源
最近更新 更多