微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

需要一些帮助来处理我从 json 服务器收到的响应

如何解决需要一些帮助来处理我从 json 服务器收到的响应

我正在 React Native 中开发一个应用程序,我试图在其中显示一些由我使用 json 服务器设置的虚假 API 提供的数据。我正在使用 useContext 钩子来处理应用程序的一般状态,而且由于我对 React Native 和 React 总体上还是很陌生,所以我需要一些帮助来处理我通过上下文 API 处理的响应。

这是我在context文件夹中设置的State文件

import React,{ useReducer } from 'react'
import MenusReducer from './MenusReducer'
import MenusContext from './MenusContext'
import { baseUrl } from '../../shared/baseURL'

const Menusstate = (props) => {
    const initialState = {
        menus: [],selectedMenu: null
    }

    const [state,dispatch] = useReducer(MenusReducer,initialState)

    const getMenus = async () => {
        const response = await fetch(baseUrl + 'RESTAURANTES')
        const data = await response.json()
        console.log('This is the reducer working'); // This is a test log to see if it works
        dispatch({
            type: 'GET_MENUS',payload: data
        })
    }

    const getDetails = async (id) => {
        const response = await fetch(`${baseUrl}RESTAURANTES/${id}`)
        const data = await response.json()
        dispatch({
            type: 'GET_DETAILS',payload: data
        })
    }

    return (
        <MenusContext.Provider value={{
            menus: state.menus,selectedMenu: state.selectedMenu,getMenus,getDetails
        }}>
            {props.children}
        </MenusContext.Provider>
    )
}

export default Menusstate;

所以在这里我设置了一个 getMenus() 函数,通过它我可以获取我想要在我的组件中显示的所有项目。如您所见,我在函数中放置了一个测试日志,以查看它是否有效,并且确实有效。

当我尝试将这些项目放入我的应用程序组件时,问题就出现了。这是我尝试让项目显示的实例之一。

const Home = ({ navigation }) => {
    const { menus,getMenus } = useContext(MenusContext)
    const [search,setSearch] = useState('')
    const [response,setResponse] = useState([])
    const [categories,setCategories] = useState(allCategories)
    const [loading,setLoading] = useState(true)

    useEffect(() => {
        const data = async () => await getMenus();
        console.log('This is the app executing');
        setLoading(false);
        setResponse(data)
        console.log(response);
    },[])
    
    // ... some code later
    
    return (
            <ScrollView style={styles.yScroll}>
                <View>
                    <Text style={styles.sectionTitle}>Destacados</Text>
                </View>
                <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                    <View style={styles.sectionContainer}>
                        <Text>{response[0]}</Text> // Here's where I'm trying to print something about the response but it's not working
                    </View>
                </ScrollView>
                <View>
                    <Text style={styles.sectionTitle}>Categorias</Text>
                </View>
                <View style={styles.sectionContainer}>
                    {categories.map((item,index) => {
                        return (
                            <View  key={index} style={styles.category}>
                                <Text>{item}</Text>
                            </View>
                        )
                    })}
                </View>
            </ScrollView>
    )
}

因此,在其中一个 ScrollView 中,我正在设置测试以查看是否可以显示响应,但事实并非如此。但是,在 useEffect 内部,我正在设置一个测试日志,其中包含消息“这是正在执行的应用程序”,但是,正在记录的响应是一个空数组。

我确定我面临的问题与应用程序和服务器之间的异步响应有关,但我不清楚如何解决这个问题。

有人能指出我正确的方向吗?提前致谢!!

解决方法

根据你的代码,我认为你可以做到这一点

const Home = ({ navigation }) => {
const { menus,getMenus } = useContext(MenusContext)
const [search,setSearch] = useState('')
const [categories,setCategories] = useState(allCategories)
const [loading,setLoading] = useState(true)

useEffect(() => {
    const data = async () => await getMenus();
    console.log('This is the app executing');
    data();
    setLoading(false);
    
},[])

// ... some code later

return (
        <ScrollView style={styles.yScroll}>
            <View>
                <Text style={styles.sectionTitle}>Destacados</Text>
            </View>
            <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                <View style={styles.sectionContainer}>
                    <Text>{menus[0]}</Text> // Here's where I'm trying to print something about the response but it's not working
                </View>
            </ScrollView>
            <View>
                <Text style={styles.sectionTitle}>Categorias</Text>
            </View>
            <View style={styles.sectionContainer}>
                {categories.map((item,index) => {
                    return (
                        <View  key={index} style={styles.category}>
                            <Text>{item}</Text>
                        </View>
                    )
                })}
            </View>
        </ScrollView>
)

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?