如何在React Native中以状态存储JSON项



我一直对react native感到困惑,我希望社区能帮助解决这个问题。我试图从API接收一些公告的列表,并将每个公告显示在一个平面列表中。

我可以接收和解析JSON,可以显示在状态中编码的项,但在状态中存储JSON数据时遇到了问题。

所以问题是:如何将从API以JSON形式接收的数据存储在react native状态?

这是我的代码(我试图修剪它,里面可能有一些jank,很抱歉(

import { StatusBar } from 'expo-status-bar';
import * as React from 'react';
import { useState } from 'react';
import { FlatList, Text, View, StyleSheet, TouchableOpacity, Image } from 'react-native';
import { createDrawerNavigator } from '@react-navigation/drawer';
import Announcement from '../components/Announcement';
import BottomBar from '../components/BottomBar';
import TopBar from '../components/TopBar';
state = {
data: [
{title: 'This is a title', text:'yadda yadda'},
{title: 'yup, still a title', text:'blah blah blah'},
{title: 'tidal', text:'Lots and lots of details'}
],
}
function AnnouncementsScreen(props) {
//const [count, setCount] = useState(0);



fetch('https://eo9260z47k.execute-api.us-east-2.amazonaws.com/default/getAnnouncements', {
method: 'GET',
headers: {
// Accept: 'application/json',
'x-api-key': 'kezCnfAATA2cs6bHh39sg4IEXvPkfnaM220seEk2',
'Content-Type': 'application/json',
},       
})
.then((response) => response.json())
.then((responseJson) => {
//This was a bit of a failed attempt
//setCount(responseJson.toString())
//console.log("state: " + state)



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


return (
<View style={styles.background}>
<View style={styles.mainContent}>
<View style = {styles.announcementsWrapper}>
<Text style = {styles.sectionTitle}>Announcements</Text> 

<View style = {styles.announcementList}>

<FlatList
data = {state.data}
keyExtractor={(x, i) => i.toString()}
renderItem={({item}) => <Announcement  title = {item.title} text = {item.text}/>}
/>
</View>
</View>
</View>
</View>

);
}
export default AnnouncementsScreen;

const Drawer = createDrawerNavigator();
const styles = StyleSheet.create({
background:{
flex: 1,
backgroundColor: '#2d0f4c',
alignItems: 'flex-start',
justifyContent: 'flex-start',
},
announcementsWrapper : {
paddingTop: 20,
paddingHorizontal:20,
},
announcementList:{
color: '#f1cf5b',
fontSize: 24,
},
sectionTitle:{
color: '#f1cf5b',
fontSize:45,
fontWeight: 'bold',
},
mainContent: {
flex: 8,
},
});

JSON看起来像这个

Object {
"0": Array [
"11001",
"1",
"Test Announcement",
"This is a test announcement to prove that the database works",
"2021-03-18 19:30:00",
],
"1": Array [
"01001",
"2",
"Lost socks",
"I have lost my favorite socks. If you find them, please let me know",
"2021-03-22 10:30:00",
],
"2": Array [
"10101",
"3",
"Found Socks",
"Please disreguard the previous statement. I found my missing socks.",
"2021-03-18 19:30:00",
],
"3": Array [
"01101",
"4",
"TestAnno",
"Something or other",
"2021-01-20 11:20:00",
],
"4": Array [
"11100",
"5",
"asdfasdfsadfasfd",
"asdfasdfasdfsadf",
"2021-04-21 15:38:44",
],
}

您应该使用useState将状态存储在函数组件内部:https://reactjs.org/docs/hooks-state.html

您的fetch调用应该在useEffect内部完成——否则,它将发生在每个渲染上:https://reactjs.org/docs/hooks-effect.html

内部function AnnouncementsScreen(props) {:

const [data, setData] = useState();
useEffect(() => {
fetch('https://eo9260z47k.execute-api.us-east-2.amazonaws.com/default/getAnnouncements', {
method: 'GET',
headers: {
// Accept: 'application/json',
'x-api-key': 'kezCnfAATA2cs6bHh39sg4IEXvPkfnaM220seEk2',
'Content-Type': 'application/json',
},       
})
.then((response) => response.json())
.then((responseJson) => {
setData(responseJson)
})
.catch((error) => {
console.error(error);
});
},[]);

然后,您可以通过在视图层次结构中使用data来访问您设置的状态。因为您返回的JSON与您现在使用的测试状态有很大的不同,所以您需要以不同的方式构建Announcement组件和/或道具,但这至少应该让您开始存储状态。

最新更新