【问题标题】:Can't find variable: method找不到变量:方法
【发布时间】:2018-04-27 01:42:52
【问题描述】:

抱歉,我对原生和 es6 反应不熟悉,现在我的 API 获取函数有问题。

componentDidMount() {
      console.log("here");
      this._onPressButtonGET(0)
    }


  renderList = (data) =>{
    if(data){
      return data.map((item) => {
        return(
          {
            rOrder: item.rOrder,
            title: item.title,
            intro: item.intro,
            url: item.url,
            img: item.img,
          }
        )
      }
    )
  }
}

  async _onPressButtonGET(data) {
    console.log("here1");
    try {
        let response = await fetch(api.novel, method:"GET")
        let json = await response.json()
        console.log("here2");

        let dataList = this.renderList(responseData.data.carousel);

        for (  data = 0 ; data < 5; data++){
          if (dataList[data] == null) break;
          console.log(dataList[i]);
        };

        this.setState({ pValue:data })

      } catch (error) {
        console.log("here3");
        this.setState({ refreshing: false })
        alert(error)
      }
  }

上面的警报给我 ReferenceError:Can't find variable: method。 console.log “这里 2” 不工作。我可以在没有 async/await 方法的情况下成功获取数据,但目前,我有点需要 async/await。请帮我完成这些功能。

 _onPressButtonGET(data) {
          fetch(api.novel, {method: "GET"})
          .then((response) => response.json())
          .then((responseData) => {
               let dataList = this.renderList(responseData.data.carousel);
               //console.log(dataList);
               //console.log(dataList[1]);
               //let i = 0;
               for (  data = 0 ; data < 5; data++){
                 if (dataList[data] == null) break;
                 //console.log(dataList[i]);
               };
               console.log("outloop" +data);
               this.setState({ pValue:data })
          })
          .done();

      }

我使用另一个函数来使这次获取成功,但不是使用 async/await。现在我很好奇这是如何工作的?为什么 async/await 不起作用?

【问题讨论】:

    标签: javascript react-native ecmascript-6


    【解决方案1】:

    错误在这一行:

    let response = await fetch(api.novel, method:"GET")
    //                                    ^
    

    method 在引号之外,作为变量名,但从未在任何地方声明过。

    您可能打算将init object 传递给fetch API

    let response = await fetch(api.novel, { method: "GET" })
    //                                    ^ passing an object, notice the { }
    

    您也可以省略方法类型(默认为“GET”):

    let response = await fetch(api.novel)
    

    【讨论】:

    • 解决了我的问题!非常感谢您,先生!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多