使用useEffect反应本机fetchdata,但获取ReferenceError:找不到变量:getListOfRecipe

时间:2020-11-02 02:38:32

标签: react-native rest axios use-effect

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

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数据吗?

1 个答案:

答案 0 :(得分:1)

useEffect()中运行函数时,需要调用它,仅在useEffect()中定义它就不会运行它。

第二,当您要打印以状态存储的值时,可以使用定义的useState的第一元素来访问它们。在这里,您可以使用setRecipesList设置数据,然后使用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