如何在 React-Native 中解析 JSON 响应
How to parse a JSON Response in React-Native
我收到来自 Django REST API 的 JSON 响应,如下所示:
[
{"email": "email1@gmail.com", "fullname": "fn1", "id": 1},
{"email": "email2@gmail.com", "fullname": "fn2", "id": 2},
{"email": "email3@gmail.com", "fullname": "fn3", "id": 3},
{"email": "email4@gmail.com", "fullname": "fn4", "id": 4},
{"email": "email5@gmail.com", "fullname": "fn5", "id": 5}
]
我想在 React native 中解析它我使用了这段代码,但它对我不起作用我不知道为什么!
我对这个框架有点陌生
import React , { useEffect, useState } from 'react';
import { View, ScrollView, Text,ActivityIndicator } from 'react-native';
const Information: () => React$Node = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
fetch('http://192.168.1.18:8000/api/User')
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
return (
<>
<ScrollView>
<View>
{isLoading ? <ActivityIndicator/> : (
<View
data={data}
renderItem={({ item }) => (
<Text >{item.id},{item.email},{item.fullname}</Text>
)}
/>
)}
</View>
</ScrollView>
</>
);
};
export default Information;
这里有一个例子 FlatList
:
return (
<SafeAreaView>
<FlatList
data={data}
renderItem={({ item }) => <Text>{item.email} ... and other stuff</Text>}
keyExtractor={item => item.id}
/>
</SafeAreaView>
)
我收到来自 Django REST API 的 JSON 响应,如下所示:
[
{"email": "email1@gmail.com", "fullname": "fn1", "id": 1},
{"email": "email2@gmail.com", "fullname": "fn2", "id": 2},
{"email": "email3@gmail.com", "fullname": "fn3", "id": 3},
{"email": "email4@gmail.com", "fullname": "fn4", "id": 4},
{"email": "email5@gmail.com", "fullname": "fn5", "id": 5}
]
我想在 React native 中解析它我使用了这段代码,但它对我不起作用我不知道为什么!
我对这个框架有点陌生
import React , { useEffect, useState } from 'react';
import { View, ScrollView, Text,ActivityIndicator } from 'react-native';
const Information: () => React$Node = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
fetch('http://192.168.1.18:8000/api/User')
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
return (
<>
<ScrollView>
<View>
{isLoading ? <ActivityIndicator/> : (
<View
data={data}
renderItem={({ item }) => (
<Text >{item.id},{item.email},{item.fullname}</Text>
)}
/>
)}
</View>
</ScrollView>
</>
);
};
export default Information;
这里有一个例子 FlatList
:
return (
<SafeAreaView>
<FlatList
data={data}
renderItem={({ item }) => <Text>{item.email} ... and other stuff</Text>}
keyExtractor={item => item.id}
/>
</SafeAreaView>
)