首页 > 解决方案 > 使用 useEffect 对本机 fetchdata 做出反应,但得到 ReferenceError:找不到变量:getListOfRecipe

问题描述

我正在尝试使用在我的反应本机应用程序中获取数据,useEffect但出现以下错误:

ReferenceError:找不到变量:getListOfRecipe。

我试图找到如何使用,useEffect但我无法解决它。

这是我的组件:

const RecipeCard = ({ }) => {
  const [recipeList, setRecipeList] = useState([])
  useEffect(() => {
    function getListOfRecipe(){
      axios({
        method: 'get',
        url: 'http://192.168.0.7:3333/report',
        responseType: 'json',
        headers: {},
        data: {
          name: "acem"
        }
      })
        .then(function (res) {
          setRecipeList(res)
        })
        .catch(function (error) {
          console.log(error);
          console.log("######## CARD CALL - ERROR!!! :: ", error);
        })
        .then(function () {
        });
    } []
  })
    
  console.log('getListOfRecipe: ', getListOfRecipe())
  
  return (
    <View>
      <Text>
        Recipe Card:
      </Text>
    </View>
  )
}

export default RecipeCard

谁能帮我修复它并进行 api fetch 调用以获取 API 数据?

标签: react-nativerestaxiosuse-effect

解决方案


当你在 a 中运行一个函数时,useEffect()你需要调用它,只是在里面定义它useEffect()不会运行它。

其次,当您要打印存储在 state 中的值时,您可以使用useState您定义的第一个元素访问它们。在这里,您使用setRecipesListthen 设置数据以便访问您使用的数据recipeList

但是当您从 API 获取数据时,数据不会立即设置。因此,您检查数据是否存在然后使用if语句然后您console.log(recipeList)

const RecipeCard = ({ }) => {
  const [recipeList, setRecipeList] = useState([])
  useEffect(() => {
    function getListOfRecipe(){
      axios({
        method: 'get',
        url: 'http://192.168.0.7:3333/report',
        responseType: 'json',
        headers: {},
        data: {
          name: "acem"
        }
      })
        .then(function (res) {
          setRecipeList(res)
        })
        .catch(function (error) {
          console.log(error);
          console.log("######## CARD CALL - ERROR!!! :: ", error);
        })
    getListOfRecipe();   
    } []
  })
    
  if(recipeList){
      console.log(recipeList)
  }

  
  return (
    <View>
      <Text>
        Recipe Card:
      </Text>
    </View>
  )
}

export default RecipeCard

推荐阅读