react-native - 使用 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 数据?
解决方案
当你在 a 中运行一个函数时,useEffect()
你需要调用它,只是在里面定义它useEffect()
不会运行它。
其次,当您要打印存储在 state 中的值时,您可以使用useState
您定义的第一个元素访问它们。在这里,您使用setRecipesList
then 设置数据以便访问您使用的数据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
推荐阅读
- python - 如何使带有变量的 Django url 模板找到正确的 url
- android - 如何从 arrayadapter 中获取值以将其传递给另一个活动
- java - 如何匹配字符串中任何位置的非单词字符?
- asp.net-core - 身份核心,持久登录不是持久的
- css - 当用户在 Django i18n 翻译中更改语言时如何提供不同的 CSS 文件
- ruby - 根据用例将不同的模块包含到同一个类中
- powershell - 任务调度程序任务未执行 ps1 脚本
- c# - 如何通过按键盘上的单个键来防止调用多个 KeyDown 事件?
- sql - 如何在 SQLite 中根据语言选择获取所有数据
- reactjs - React Native WebView 没有加载 react js 站点(内置 react js)?