嗨,我是新来的本地人。我正在尝试调用任何api,但无法在应用程序屏幕上看到任何数据,但可以在控制台上看到数据。我认为此问题与我的状态有关,但是每当我尝试在该状态上添加任何内容时,它都会给我一个响应“ json.data”不是对象。请对此进行指导。谢谢。
export default App = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://URL', {
method: 'GET',
timeout: 10000,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"this": "",
"this 2": ""
})
})
.then((response) => response.text())
.then((responseData) => { console.log(responseData); })
.then((json)=> setData(text(json.data)))
.catch((error) => console.error(error))
.finally(() => setLoading(false)); [];
}, []);
return (
<ScrollView style={styles.container}>
{isLoading ? <ActivityIndicator /> : (
<Text> {data.text} </Text>
<FlatList
data={data}
renderItem={({ item }) => (
<Text>{item.skill}</Text>
)}
/>
)}
</ScrollView>
);
};
答案 0 :(得分:1)
您必须先解析JSON,然后才能显示:
编辑:我将response.text()
替换为response.json()
,以正确处理JSON(例如:解析)。
export default App = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://URL', {
method: 'GET',
timeout: 10000,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"this": "",
"this 2": ""
})
})
.then((response) => response.json())
.then((data) => setData(json.data))
.catch((error) => console.error(error))
.finally(() => setLoading(false)); [];
}, []);
return (
<ScrollView style={styles.container}>
{isLoading ? <ActivityIndicator /> : (
<FlatList
data={data}
renderItem={({ item }) => (
<Text>{item.skill}</Text>
)}
/>
)}
</ScrollView>
);
};