react-native - Axios 获取响应未转移到状态 [Native React]
问题描述
这里的第一个问题。
当我尝试运行它时,它确实在 response.data 中获取数据,但是该数据未设置为作为道具传递到另一个页面的状态,并且它始终保持 [Object object] 或 [undefined] 并且我没有提示出了什么问题
state = {
APiData: {},
userInput: "cheese",
onCall: false
}
findFood = () => {
let self = this;
let userInput = this.state.userInput.toLowerCase();
let url = "https://api.spoonacular.com/recipes/search?query=" + userInput + "&number=1&apiKey="+apiKey;
axios.get(url)
.then(function (response) {
console.log(response.data); //get's data
self.setState({APIdata: response.data});
})
.catch(function (error) {
console.log(error)
});
}
renderbody = () => {
console.log(this.state.APIdata) //this thing, is undefined
// return (<SearchBody data={this.state.APIdata} key={apiKey}/>)
}
这是 response.data 中的数据
"baseUri": "https://spoonacular.com/recipeImages/",
"expires": 1585843318293,
"isStale": false,
"number": 1,
"offset": 0,
"processingTimeMs": 437,
"results": Array [
Object {
"id": 215435,
"image": "three-cheese-pizza-for-cheese-lovers-215435.jpg",
"imageUrls": Array [
"three-cheese-pizza-for-cheese-lovers-215435.jpg",
],
"readyInMinutes": 45,
"servings": 8,
"title": "Three-Cheese Pizza (For Cheese Lovers)",
},
],
"totalResults": 855,
}
Object {
"baseUri": "https://spoonacular.com/recipeImages/",
"expires": 1585843318293,
"isStale": false,
"number": 1,
"offset": 0,
"processingTimeMs": 437,
"results": Array [
Object {
"id": 215435,
"image": "three-cheese-pizza-for-cheese-lovers-215435.jpg",
"imageUrls": Array [
"three-cheese-pizza-for-cheese-lovers-215435.jpg",
],
"readyInMinutes": 45,
"servings": 8,
"title": "Three-Cheese Pizza (For Cheese Lovers)",
},
],
"totalResults": 855,
}
解决方案
您没有使用状态。您的状态需要在您的构造函数中
constructor(props) {
super(props);
this.state = {
APiData: {},
userInput: "cheese",
onCall: false
}
}
然后,你只需要打电话this.setState({ APIdata: response.data });
我会推荐你使用react-redux来使用 this.props 获取数据。
推荐阅读
- html - 在 Firefox 打印上看不到表格边框
- php - 谷歌文档查看器在 php 中显示“没有可用的预览”
- c++ - reinterpret_cast 发送的数据
- javascript - 如何使滑块自动移动?
- javascript - 如何显示字符串中的第二个数组来自 .split()
- javascript - 我可以使用 javascript 中的值以外的任何内容设置选择选项吗
- saml - 我需要将哪个身份提供程序用于 SAML 工件绑定
- javascript - 如何在鼠标单击时突出显示行?
- chart.js - 无法更新图表
- delphi - TVirtualStringTree 显示不正确的数据,即在每个单元格中显示“节点”。如何显示正确的数据?