首页 > 解决方案 > 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,
}


标签: react-nativeaxios

解决方案


您没有使用状态。您的状态需要在您的构造函数中

constructor(props) {
   super(props);
   this.state = {
       APiData: {},
       userInput: "cheese",
       onCall: false
   }
}

然后,你只需要打电话this.setState({ APIdata: response.data });

我会推荐你​​使用react-redux来使用 this.props 获取数据。


推荐阅读