在没有ListView的情况下呈现JSON数据?

时间:2018-02-05 20:12:03

标签: json react-native

我一直在查看其他问题,例如Display JSON into listview which has multiple json arrays,并且我一直在遇到同样的问题。我收到的错误是:evaluating 'instance.render()'在尝试转到个人资料页面时。

componentDidMount() {

  return fetch('http://www.example.com/React/user-list.php')
    .then((response) => response.json())
    .then((responseJson) => {
      let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
      this.setState({
        isLoading: false,
        dataSource: ds.cloneWithRows(responseJson),
      }, function() {
        // In this block you can do something with new state.
      });
    })
    .catch((error) => {
      console.error(error);
    });
  }



  renderRow = (rowData) => {


      return(
         <View style = { styles.MainContainer }>

            <Text> </Text>

            <Button
            style = {{ justifyContent: 'center', alignItems: 'center' }}
            title="Click here to Logout" onPress={ this.logout } />
            <Text>{rowData.username}</Text>


         </View>
       );
     }
   }

我的目标是在不使用ListView的情况下显示数据库中的数据。虽然,我能够成功地使用ListView显示它们。

1 个答案:

答案 0 :(得分:0)

尝试使用FlatList我相信它更简单易用,而且ListView已被折旧。 您的代码应如下所示:

componentDidMount(){
    fetch('http://www.example.com/React/user-list.php')
    .then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        isLoading: false,
        dataSource: responseJson,
      }, function() {
        // In this block you can do something with new state.
      });
    })
    .catch((error) => {
      console.error(error);
    });
}

render(){
    return(
        <FlatList
            data={this.state.dataSource}
            extraData={this.state}
            keyExtractor={({row})=>row.id}
            renderItem={({rowData})=>this.renderRow(rowData)}

        />
    )
}

希望这有帮助。