当我在RN中使用flatlist时,我发现此错误:无法读取undefined的属性'loginname'

时间:2018-01-15 03:49:01

标签: react-native-ios

我只想向FlatList组件显示网站数据列表,但我发现错误:

  

TypeError:无法读取未定义

的属性“loginname”

因此,我将“{item.author.loginname}”更改为“{item.author}”,我收到此错误:

  

未处理的JS异常:不变违规:对象无效   React child(找到:带键的对象{loginname,avatar_url})。如果你想渲染一个

的集合

实际上,属性'loginname'存在。我很迷惑。为什么呢?

这是我的代码:

import React, { Component } from 'react';
import { Text, ScrollView, View, StyleSheet, FlatList,Image } from 'react-native';
export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      stories: [{id: 1, text: 'option1'}, {id: 2, text: 'option2'}, {id: 3, text: 'option3'}],
      isFetching: false,
    };
  }
  componentDidMount() {
    this.fetchData();
  }
  onRefresh() {
    console.log('refreshing')
    this.setState({ isFetching: true }, function() {
      this.fetchData()
    });
  }
  fetchData() {
    var url = "https://cnodejs.org/api/v1/topics?limit=1&mdrender=true"
          fetch(url, {method: "GET"})
          .then((response) => response.json())
          .then((responseData) => {
               this.setState({stories: responseData.data,isFetching: false})
               console.log( responseData.data[0].author.loginname,responseData.data[0].visit_count)
          })
          .done();
  }
  _renderItem = ({item}) => (
    <View>
    <Text>{item.author.loginname}</Text>
    </View>
  )
  render() {
    return (
      <ScrollView style={styles.container}>
        <View style={styles.wrapper}>
        <Text>Hello World!!!</Text>
          <FlatList
            onRefresh={() => this.onRefresh()}
            refreshing={this.state.isFetching}
            data={this.state.stories}
            keyExtractor={(item) => item.id}
            renderItem={this._renderItem}
          />
        </View>
      </ScrollView>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    // alignItems: 'center',
    // justifyContent: 'center',
    paddingTop: 50,
    backgroundColor: '#ecf0f1',
  }
});

2 个答案:

答案 0 :(得分:1)

出现此问题的原因是您在构造函数中设置的初始状态。当第一次组件试图在那时渲染时,它会解决故事问题。从构造函数状态,因为你的API提取时刻完成调用。

只需按照以下行替换您的构造。

constructor(props) {
    super(props);
        this.state = {
          stories: [],
          isFetching: false,
    };
}

答案 1 :(得分:0)

发生此问题的原因是您的视图首先加载,然后调用api。所以你的故事是不确定的。

代码的小更新:

this.state = {
      stories: null,
      isFetching: false,
    };

在渲染中查看:

render() {
    return (
      <ScrollView style={styles.container}>
        <View style={styles.wrapper}>
        <Text>Hello World!!!</Text>
        {this.state.stories !== null ?      
          <FlatList
            onRefresh={() => this.onRefresh()}
            refreshing={this.state.isFetching}
            data={this.state.stories}
            keyExtractor={(item) => item.id}
            renderItem={this._renderItem}
          />
          : null
  }
        </View>
      </ScrollView>
    );
  }

输出:

Hello World!!
atian25