我是 reactjs 的新手,我正在使用 create-react-app 开始,但我不明白如何进行 api 调用来获取数据。这是我的代码:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
// import { URL, KEY, city, countryCode } from './config.json';
const KEY = "d7ba7d7818dd3cec9ace78f9ad55722e";
const URL = "api.openweathermap.org/data/2.5";
const CITY = "Paris";
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentDidMount() {
var url = `${URL}/weather?q=${CITY}&APPID=${KEY}&units=metric`;
console.log(url);
fetch(url).then(
response => response.json()
).then(
json => {
console.log(json);
this.setState({data: json});
}
);
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
render 方法只是 create-react-app 的默认渲染,我没有更改它。我只添加了构造函数和 componentDidMount 方法。我尝试从 OpenWeatherMap API 获取一些数据,将其添加到状态并将其记录到控制台。
该请求在邮递员中完美运行,但在我的应用程序中引发此错误:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
谁能帮我 ?