简体   繁体   English

如何在 React Native 中的 state 中存储 JSON 项目

[英]How to store JSON items in state in React Native

I've been having some confusion with react native, and I'm hoping the community can help clear it up.我一直对 react native 有一些困惑,我希望社区可以帮助解决它。 I'm attempting to receive a list of some number of announcements from an API, and display each announcement in a flatlist.我正在尝试从 API 接收一些公告的列表,并在平面列表中显示每个公告。

I can receive and parse the JSON, I can display Items that are coded in state, but I'm having trouble storing JSON data in state. I can receive and parse the JSON, I can display Items that are coded in state, but I'm having trouble storing JSON data in state.

So the question is this: How can I store data received as a JSON from an API, in state in react native?所以问题是这样的:我如何将来自 API 的 JSON 接收到的数据存储在 state 中?

This is my code (which I tried to trim, there may be some jank in there, sorry about that)这是我的代码(我试图修剪,那里可能有一些卡顿,对此感到抱歉)

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,
    },
});

And the JSON lookes like this 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",
  ],
}

You should use useState to store state inside a function component: https://reactjs.org/docs/hooks-state.html You should use useState to store state inside a function component: https://reactjs.org/docs/hooks-state.html

The fetch call that you have should be done inside useEffect -- otherwise, it'll happen on each render: https://reactjs.org/docs/hooks-effect.html您的fetch调用应该在useEffect中完成——否则,它会在每次渲染时发生: https://reactjs.org/docs/hooks-effect.html

Inside function AnnouncementsScreen(props) { :里面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);
});
},[]);

Then, you can access the state that you've set by using data inside your view hierarchy.然后,您可以使用视图层次结构中的data访问您设置的 state。 Because the JSON that you're getting back is significantly different than the test state that you're using right now, you'll need to structure your Announcement component and or props differently, but this should get you started on at least storing the state.因为您返回的 JSON 与您现在使用的测试 state明显不同,您需要以不同的方式构建您的Announcement组件和/或道具,但这应该让您至少开始存储 Z95ED39E2EA9A9EZEF88 .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 React Native 的 state 中存储一个值? - How to store a value in a state in React Native? 如何对要添加到 React Native Context 的 State 的项目进行排队 - How to Queuing Items to be added into React Native Context's State 如何 select 列表中的项目并将其存储在 state React Native - How to select an item from list and store it on the state React Native 如何将 1d 转换为 2d 并将其存储在 react native state 中? - How to convert 1d into 2d and store it in a react native state? how to create an array of JSON objects, store them in a state array object and print the elements inside the render function in react-native - how to create an array of JSON objects , store them in a state array object and print the elements inside the render function in react-native React Native,将项目推送到数组 state 不起作用 - React Native, pushing items to an array state not working React Native在状态数组中添加新项目 - React native add new items in state array React Native - 如何解析json数据并将其设置在状态对象中 - React Native - How to parse json data and set it in a state object 如何在React Native上访问数组状态或JSON数据? - How to access array state or json data on react native? 如何从react-native中的状态动态访问json常量 - How to access json constant dynamically from a state in react-native
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM