React Native:如何在渲染屏幕时或之前立即获取数据?

时间:2020-09-02 06:59:27

标签: javascript reactjs react-native

我是这样做的,但是现在我需要在调用函数之前保护文件的安全。当用户切换到屏幕时,我需要它立即被调用,因为将显示的项目来自提取。

useLayoutEffect(() => {
    async function getUserData() {
      var ingredients = await firebase.firestore().doc("ingredients/" + user.uid).get();
      var labels = []
      ingredients.data().ingredients.forEach(ingredient => {
        labels.push(ingredient.label)
      })
      setUserIngredients(labels)
      console.log(userIngredients)
      setUserRecipes([])
    }
    getUserData()
    fetchRecipes(userIngredients)
  }, [])

这是fetchRecipes函数

function fetchRecipes(userIngredients) {
    var number = 5
    var url = "https://api.spoonacular.com/recipes/findByIngredients?ingredients=" + userIngredients.join(",") + "&number=" + String(number) + "&apiKey=" + apiKey
    fetch(url, {
      method: "GET"
    }).then((response) => response.json())
      .then((responseJson) => {
        for (var i = 0; i < number; i++) {
          var newRecipe = {
            id: responseJson[i].id,
            title: responseJson[i].title,
            image: responseJson[i].image,
            ingredients: userIngredients
          }
          userRecipes.unshift(newRecipe)
        }
        firebase.firestore().doc("ingredients/" + user.uid).update({
          recipes: userRecipes
        })
        console.log("Rezepte", userRecipes)
      }).catch((error) => {
        console.error(error);
      })
  }

1 个答案:

答案 0 :(得分:0)

需要一些更改:

  1. 您可以更改您使用的react挂钩,最好使用useEffect挂钩,因为您在那里没有使用任何dom突变
  2. 您可以实现自定义钩子
import React, { useState, useEffect } from 'react';

const useFetch = (targetUrl) => {
  const [data, setData] = useState(null);
  useEffect(() => {
    async function fetchData() {
      const response = await fetch(targetUrl);
      const json = await response.json();
      setData(json);
    }
    fetchData();
  }, [targetUrl]);

  return data;
};

const App = () => {
    const URL = 'https://api.spoonacular.com/recipes/findByIngredients?ingredients=" + userIngredients.join(",") + "&number=" + String(number) + "&apiKey=" + apiKey';
    const result = useFetch(URL);

    return (
      <div>
        {JSON.stringify(result)}
      </div>
    );
}