在 React 中使用 JS ES6 承诺的问题 - TypeError:无法读取未定义的属性“then”

装甲坦克

getWeather从我编写的另一个 .js 文件中导入该函数结果是一个 json blob。我已经验证我得到了 JSON blob,但是当我尝试调用该getWeather函数并使用 .then 等待响应并设置我的状态时,我得到了一个 TypeError。

getWeather(parseFloat(lat),parseFloat(long)).then((data) =>{
  this.setState({weatherType: data.currently.icon, temp: data.currently.temperature})
  return data
}).catch((error) => {
  console.log(error.message);
})

getWeather功能是在这里:

export function getWeather(lat,long) {
  const params = {
    headers: {
      "content-type": "application/json; charset=UTF-8",
      "Access-Control-Allow-Origin": "*"
    },
    method: "GET"
      };
      fetch(`https://api.com/mykey/${lat},${long}`, params)
        .then(function (data) {
          return data.json();
        })
        .then(res => {
          console.log(res);
        })
        .catch(error => {
          console.log(error);
        });
    }
D 低

您需return fetch()要这样做才能从另一个函数访问承诺。另外,我可能会在调用函数中处理日志记录和错误,因为当您记录数据时不再返回它。

export function getWeather(lat,long) {
  const params = {
    headers: {
      "content-type": "application/json; charset=UTF-8",
      "Access-Control-Allow-Origin": "*"
    },
    method: "GET"
      };
      return fetch(`https://api.com/mykey/${lat},${long}`, params)
        .then(function (data) {
          if (!data.ok) { return new Error('custom error message here') }
          return data.json();
        });
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

React Js Uncaught(承诺)TypeError:无法读取未定义的属性

在React js中使用map函数时,始终出现错误“ TypeError:无法读取未定义的属性'map'”

React js TypeError:无法读取未定义的属性“params”

React TypeError:无法读取未定义问题的属性“categoryName”

在 React.js 中使用 execCommand 时无法读取未定义的属性“contentDocument”

无法使用 Firebase v9 Modular React JS 读取未定义的属性(读取“indexOf”)

无法使用this.function(React.js)读取未定义的属性“ function”

类型错误:无法使用 React js 读取未定义的属性“0”

React 中的 Jest 测试承诺给出了 TypeError:无法读取未定义的属性“最终”

React + Axios:未捕获(承诺)TypeError:无法读取未定义的属性“map”

React Redux-未捕获(承诺)TypeError:无法读取未定义的属性“ props”

在ES6 React .JS中使用Async / Await

topojson / d3.js:未捕获(承诺)TypeError:无法读取未定义的属性“ type”

Tensorflow.js:未捕获(承诺)TypeError:无法读取未定义的属性'length'

无法在Mac上运行React JS。'TypeError:无法读取未定义的属性'render'

React Hooks问题:无法处理的拒绝(TypeError):无法读取未定义的属性“ signup”

使用 es6 和 react 的未定义函数

TypeError:无法读取未定义React.js的属性“ map”

React.js错误:TypeError:无法读取未定义的属性'map'

React.JS TypeError:无法读取未定义的属性“编号”-(在 setState 中)

Uncaught TypeError:无法读取未定义的属性“ map”-React js

React.js:TypeError:无法读取未定义的属性'eventSlots'

我遇到TypeError:无法读取未定义的属性“ GoogleAuthProvider”?(React JS)Firebase?

React.js:未捕获的TypeError:无法读取未定义的属性“任务”

未捕获的TypeError:无法读取REACT JS中未定义的属性“值”

已解决/React.js TypeError:无法读取未定义[Tic Tac Toe]的属性“ 0”

React.js测试TypeError:无法读取未定义的属性“ pushState”

TypeError:无法读取国家/地区下拉列表的React JS中未定义的属性'length'

TypeError:无法读取react.js中未定义的属性'map'