【问题标题】:react native fetchdata using useEffect, but getting the ReferenceError: Can't find variable: getListOfRecipe使用 useEffect 对本机 fetchdata 做出反应,但得到 ReferenceError:找不到变量:getListOfRecipe
【发布时间】:2021-02-14 17:34:23
【问题描述】:

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

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

【问题讨论】:

  • catch() 后面的额外then() 有什么作用?我认为如果您希望从状态而不是运行函数中访问它的数据,也可以将其删除。

标签: react-native rest axios use-effect


【解决方案1】:

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

其次,当您要打印存储在 state 中的值时,您可以使用您定义的 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

【讨论】:

    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 2018-12-03
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 2018-04-24
    • 1970-01-01
    相关资源
    最近更新 更多