在 react native 中使用 json 数据填充平面列表,这是不可能的?



我对 react native 很陌生,刚刚开始掌握它的窍门。尝试从我的虚拟 api 获取 json 数据并使用它填充视图。

目前正在使用平面列表,工作正常!除非当我给它一个非常基本的 json 项目数组时它不起作用。

以下是基本 json 数据数组的外观:

[{"Note 1": "This is note number 1."}, {"Note 2": "This is note number 2."}, {"Note 3": "This is note number 3."}]

这是我正在使用的非常临时和基本的代码:

render() {
let apiData = fetch("address of my api which is not relevant, it works")
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
return responseJson;
})
.catch((error) => {
console.error(error);
});
console.log(apiData);
return (
<View style={styles.notesContainer}>
<FlatList
data={apiData}
renderItem={({ item }) => <Text style={styles.item}>{item.key}</Text>}
/>
</View>
);
}

json 数组非常简单,只包含 3 个对象。如果我创建一个随机内容列表(如文档中的"键:值"中所述,平面列表工作正常。

在我可以设置为平面列表的数据源之前,我真的需要以某种方式处理基本的 json 数组吗?

使用componentDidMount从 API 获取数据,并使用 state 存储 apiData。

所以你的代码将是这样的:

constructor () {
super(props);
state = {
apiData:[]
};
}
componentDidMount =()=>{
fetch("address of my api which is not relevant, it works")
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({apiData: responseJson});
})
.catch((error) => {
console.error(error);
});

} 
render() {
return (
<View style={styles.notesContainer}>
<FlatList
data={this.state.apiData}
renderItem={({ item }) => <Text style={styles.item}>{item.key}</Text>}
/>
</View>
);
}

最新更新