【问题标题】:Axios get response is not carried over into state [Native React]Axios 获取响应未结转到状态 [Native React]
【发布时间】:2020-04-01 13:19:30
【问题描述】:

这里是第一个问题。

当我尝试运行它时,它确实在 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,
}


【问题讨论】:

  • 对于undefined 的情况,您需要添加一些代码来处理它,因为您调用的api 并不总是能满足您的要求。所以对于response.data这部分,首先尝试检查它是否是undefined,如果有意义就给它默认值

标签: react-native axios


【解决方案1】:

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

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

然后,您只需拨打this.setState({ APIdata: response.data });

我建议您使用 react-redux 来使用 this.props 获取数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-12
    • 2021-07-27
    • 1970-01-01
    • 2020-09-27
    • 2019-02-27
    • 2019-06-27
    • 2017-02-07
    • 1970-01-01
    相关资源
    最近更新 更多