【问题标题】:React-Native Axios Request & Undefined propsReact-Native Axios 请求和未定义的道具
【发布时间】:2017-11-19 04:37:02
【问题描述】:

我正在使用 Axios 来轮询 Web api 以返回一些东西。目前,Axios 将运行 API,我可以记录下已返回正确的响应,因为 console.log 显示:

(2) [Object, Object]

但是,如果我尝试这样做

this.props.navigator.push({
    title: "Results",
    component: "SearchResults",
    passProps: {response: response}
  });

我得到一个“TypeError: Cannot read property 'props' of undefined at eval”,并在包含 this.props.navigator.push 的行给出错误em>。

相关代码:

_axiosFetch(searchString) {
    var queryURL = 'http://mourningafter.eu/DataService.php?state=get&name=' + searchString
    axios.get(queryURL)
        .then(function (response) {
          console.log(response)
          this.props.navigator.push({
               title: "Results",
               component: SearchResults,
               passProps: {response: response}
          });
        })
        .catch(function (error) {
          console.log(error)
        });
}

至少可以说我很困惑!

任何帮助都会很棒,干杯!

【问题讨论】:

    标签: json react-native axios


    【解决方案1】:

    不知道_axiosFetch 调用的上下文是什么,但我们假设它引用了您的组件。然后,关注.then(function(response){}) 回调——它改变了上下文并且不再引用组件,因此,你不能在回调中调用this.props...

    使用箭头函数将上下文绑定到回调函数中

    _axiosFetch(searchString) {
        var queryURL = 'http://mourningafter.eu/DataService.php?state=get&name=' + searchString
        axios.get(queryURL)
            .then((response) => {
              console.log(response)
              this.props.navigator.push({
                   title: "Results",
                   component: SearchResults,
                   passProps: {response: response}
              });
            })
            .catch(function (error) {
              console.log(error)
            });
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-24
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 2016-11-08
      • 2018-04-18
      相关资源
      最近更新 更多