首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >获取数据时保存数据时useState、UseEffect的问题

获取数据时保存数据时useState、UseEffect的问题
EN

Stack Overflow用户
提问于 2020-05-29 04:03:03
回答 1查看 1K关注 0票数 0

我刚开始响应本机,我希望在应用程序的欢迎屏幕上使用axios单击对api的请求,然后使用useState将数据保存在变量中,然后在另一个类(AllProductCategory .js)中使用该数据,而不必将请求返回到api。

我使用React本机0.62钩子反应导航5和axios。

我在Navigation.js文件中有以下内容。一个以useMemo作为其值的上下文,它包含一个返回,因此它返回一个数组,其中包含它使用axios从应用程序中带来的信息。这个类如下所示:在这个类中,跳过与我当前问题无关的某些代码行。

代码语言:javascript
复制
export default function Navigation() {
  const [allproducts, setAllproducts] = useState([]);

  useEffect(() => {
    const _loadAllCategories = async () => {
      await axiosClient
        .get("/service/product_available")
        .then(function (response) {
          console.log("Data antes de pasarlo al useState ", response.data);
          setAllproducts(response.data);
          console.log("Los productos son: ", allproducts);
        })
        .catch(function (error) {
          console.log("Error obteniendo el token", error);
        });
    };
    _loadAllCategories();
  }, []);

  const authContext = useMemo(
    () => ({
      getAllProducts: () => {
        return allproducts;
      },
    }),
    []
  );

  return (
    <AuthContext.Provider value={authContext}>
      {state.isLoading ? (
        <SplashStackScreen />
      ) : state.userToken == null ? (
        <PrincipalStackScreen />
      ) : (
        <MyDrawer />
      )}
    </AuthContext.Provider>
  );
}

对于这个文件,我想要的是在启动屏幕加载时加载所有产品的数据,所以当我想在另一个屏幕上使用这些数据时,只需调用上下文变量并返回数据,而不必向api发出另一个请求。

然后,在类中,我使用上下文实现了对该数据的调用。

代码语言:javascript
复制
const { getAllProducts } = React.useContext(AuthContext);
const allProducts = getAllProducts();

完整的课程如下:

代码语言:javascript
复制
import React, { useState, useEffect } from "react";
import { View, Text, FlatList, StyleSheet, TouchableOpacity, Dimensions, Image } from "react-native";
import { AuthContext } from "../../context";

var { height, width } = Dimensions.get("window");

export default function AllProductCategoryScreen() {
  const { getAllProducts } = React.useContext(AuthContext);
  const allProducts = getAllProducts();

  function Product_Category({ name, image }) {
      console.log("name e image", name);
    return (
      <View>
        <TouchableOpacity>
          <Image style={styles.imageCategory} source={{ uri: image }} />
          <Text>{name}</Text>
        </TouchableOpacity>
      </View>
    );
  }

  return (
    <View>
      <Text>Todas las categorias</Text>
      <View style={{ alignItems: "center" }}>
        <FlatList
          scrollEnabled={true}
          numColumns={2}
          data={allProducts}
          renderItem={({ item }) => (
            <Product_Category name={item.name} image={item.imagePath} />
          )}
          keyExtractor={(item, index) => index.toString()}
        />
      </View>
    </View>
  );
}

我的app.js如下:

代码语言:javascript
复制
import React from 'react';
import Navigation from "./src/components/Navigation/Navigation"

export default function App() {
  return <Navigation />
}

我目前遇到的问题是,当我启动我的应用程序时,我会显示请求是用axios发出的,它正确地带来了数据,但是useState中没有填充axios响应我的数据(它打印[])。但是,如果我将更改保存在可视化代码中的navigation.js类中,导航类的变量所有产品将正确填充数据,因此在要显示数据的另一个类中,它将正确绘制数据。

我需要当我的应用程序加载时,api带来的数据被保存,当在另一个类中使用它时,这些数据保留下来,以便可以在屏幕上使用并演示这些数据。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-29 04:12:06

当传递给useMemo的函数创建时,它捕获allproducts的第一个值,并且始终具有该值。它将始终返回[]

为了使useMemo再次运行并捕获一个新值,将该值添加到第二个参数数组中。当数组中的值发生变化时,React将调用memo函数,然后将再次创建getAllProducts并捕获allproducts的一个新值。

代码语言:javascript
复制
 const authContext = useMemo(
    () => ({
      getAllProducts: () => {
        return allproducts;
      },
    }),
    [allproducts]
  );
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62078508

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档