所以,我陷入了 React,它已经让我挠头了..
我正在抓取一些 API 数据并尝试访问任何特定索引或循环 - 无论我做什么,它似乎都不起作用!
这里是主要组件:
class App extends React.Component {
const CityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff'];
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
// Fire our function below on app load
componentDidMount() {
this.getWeather();
}
// getWeather - make api call
getWeather = () => {
let results = [];
// Loop through our cities list here to gather data
// We will then push this into this.state.results
CityListNames.forEach(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
// get api data
fetch(api_url)
.then(res => res.json())
.then(
(result) => {
results.push(result);
console.log(result[0]);
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
});
this.setState({
isLoaded: true,
items: results
});
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="weather-app">
</div>
);
}
}
}
export default App;
当我使用 console.log(result[0]);
时,它只是在控制台中输出为“undefined”。
我正在尝试将所有值分配给结果变量,然后将其推送到状态。
当我执行 console.log(items) 时,它也会显示所有项目,这很奇怪。
API 数据
任何帮助将不胜感激!
谢谢
最佳答案
在设置状态之前,您必须等待所有 api 请求解决,因此不要使用 forEach,而是使用 map,然后像这样返回日期 promise :
getWeather = () => {
// Loop through our cities list here to gather data
// We will then push this into this.state.results
Promise.all(CityListNames.map(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
return fetch(api_url)
.then(res => res.json());
})).then((results) => {
this.setState({
isLoaded: true,
items: results
});
}).catch((error) => {
this.setState({
isLoaded: true,
error
});
});
}
关于javascript - 无法访问 React Component 中的 Javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53382540/