试图从api中获取数据并在react native flatlist中显示它们,而我的代码在控制台日志中显示数据,但未在模拟器中呈现

从'react'导入React,{组件};

从“ react-native”导入{AppRegistry,StyleSheet,flatList,文本,视图,警报,activityIndi​​cator,平台};

类UserList扩展了组件{

构造函数(道具)   {

super(props);

this.state = { 
isLoading: true,

}   }

componentDidmount(){     fetch('http://000.000.0.000:0000/api/useraccount/user',{         方法:“ GET”,         标头:{             'accept':'application / json',             'Content-Type':'application / json',             'auth-token':'我的令牌'         }

})

    .then((response) => response.json())
    .then((responseJson) => {
        this.setState({
            isLoading: false,// dataSource: JSON.parse(responseJson),dataSource: JSON.stringify(responseJson) ===>i think this is were problem
             });
        if (responseJson) {
             Alert.alert("Id is" + JSON.stringify(responseJson)) ==>this give me an alert
             console.log(responseJson)
        } 
        else if (responseJson.error) {
            Alert.alert(responseJson.error);
        }

    })

    .catch((error) => {
        console.error(error);
    })
 }

flatListItemSeparator =()=> {     返回(            );   }

render(){

if (this.state.isLoading) {
  return (
    <View style={{flex: 1,paddingTop: 20}}>
      <activityIndicator />
    </View>
  );
}

return (

   <flatList

      data={ this.state.dataSource }

      ItemSeparatorComponent = {this.flatListItemSeparator}

      renderItem={({item}) => <Text > {item.name} </Text>}

      keyExtractor={(item,index) => index}

     />

);

} }

导出默认用户列表;

const styles = StyleSheet.create({

MainContainer:{

justifyContent:“中心”, flex:1, 保证金:10, paddingTop:(Platform.OS ==='ios')? 20:0,

},

flatListItemStyle:{     填充:10,     fontSize:18,     高度:44   }

});

wolaiwen_0 回答:试图从api中获取数据并在react native flatlist中显示它们,而我的代码在控制台日志中显示数据,但未在模拟器中呈现

FlatList需要一个对象数组。您正在this.state.dataSource中传递字符串。另外,如果您已经使用JSON.parse解决了响应数据,则无需再次使用response.json进行解析。

替换以下内容

dataSource: JSON.stringify(responseJson)

使用

dataSource: responseJson

确保responseJson是一个数组。

,

最终找到了解决方法...

代替Flatlist,使用列表视图呈现详细信息...

,

当您有大量数据时,建议使用平板列表而不是列表视图。当用户向下滑动以查找更多信息时,数据会相应显示。

本文链接:https://www.f2er.com/3103503.html

大家都在问