Can';无法访问React组件中的Javascript对象
所以,我陷入了React,它已经让我抓伤了我的头 我正在抓取一些API数据,比如,并试图访问任何特定的索引或循环-无论我做什么,它似乎都不起作用 以下是主要组成部分:Can';无法访问React组件中的Javascript对象,javascript,arrays,json,reactjs,Javascript,Arrays,Json,Reactjs,所以,我陷入了React,它已经让我抓伤了我的头 我正在抓取一些API数据,比如,并试图访问任何特定的索引或循环-无论我做什么,它似乎都不起作用 以下是主要组成部分: class App extends React.Component { const CityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff']; constructor(props) { super(props
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;
类应用程序扩展了React.Component{
const CityListNames=[“彼得堡”、“曼彻斯特”、“布莱顿”、“利物浦”、“加的夫”];
建造师(道具){
超级(道具);
此.state={
错误:null,
isLoaded:false,
项目:[]
};
}
//在应用程序加载时启动下面的功能
componentDidMount(){
这个。getWeather();
}
//getWeather-进行api调用
getWeather=()=>{
让结果=[];
//在此处循环浏览我们的城市列表以收集数据
//然后我们将把它推到this.state.results
CityListNames.forEach(函数(名称){
让api_url=”http://api.openweathermap.org/data/2.5/weather?q=“+name+”,英国&appid=“+ApiKey;
让数据;
//获取api数据
获取(api_url)
.then(res=>res.json())
.那么(
(结果)=>{
结果。推(结果);
console.log(结果[0]);
},
(错误)=>{
这是我的国家({
isLoaded:是的,
错误
});
}
);
});
这是我的国家({
isLoaded:是的,
项目:结果
});
}
render(){
const{error,isLoaded,items}=this.state;
如果(错误){
返回错误:{Error.message};
}否则,如果(!已加载){
返回装载。。。;
}否则{
返回(
);
}
}
}
导出默认应用程序;
当我使用console.log(结果[0])代码>它只是在控制台中输出为“未定义”
我试图将所有值分配给results变量,然后将其推送到state
当我做console.log(items)时,它也会显示所有的项,这很奇怪
API数据
任何帮助都将不胜感激
谢谢你是说console.log(results[0])是“result”的复数形式吗。在promise中,结果是解析json响应后得到的结果。如果该响应没有键“0”(它不应该有),那么您将得到未定义
编辑
问题不是您正在进行异步调用,然后执行push和console.log的同步操作。问题在于,在控制台日志记录与推送正确响应之间存在一种打字错误
fetch(api_url)
.then(res => res.json())
.then(
(result) => {
results.push(result); // <--- pushes valid response into array
console.log(result[0]); // <--- logs undefined
},
fetch(api\u url)
.then(res=>res.json())
.那么(
(结果)=>{
results.push(result);//在设置状态之前,您必须等待所有api请求得到解决,因此,不要使用forEach,而是使用map,然后返回日期承诺,如下所示:
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
});
});
}
1.fetch:异步工作,因此当您将结果的值分配给状态时,这将是一个空数组
this.setState({
isLoaded: true,
items: results
});
前面的代码必须放在获取结果中
class App extends React.Component {
cityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff']; // this is one of the changes
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
this.getWeather();
}
getWeather = () => {
let results = [];
this.cityListNames.forEach(function (name) { //this is one of the changes
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
fetch(api_url)
.then(res => res.json())
.then((result) => {
results.push(result);
this.setState({ // this is one of the changes
isLoaded: true,
items: results
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
});
}
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;
类应用程序扩展了React.Component{
cityListNames=[“彼得堡”、“曼彻斯特”、“布莱顿”、“利物浦”、“加的夫”];//这是一个变化
建造师(道具){
超级(道具);
此.state={
错误:null,
isLoaded:false,
项目:[]
};
}
componentDidMount(){
这个。getWeather();
}
getWeather=()=>{
让结果=[];
this.cityListNames.forEach(函数(名称){//这是一个更改
让api_url=”http://api.openweathermap.org/data/2.5/weather?q=“+name+”,英国&appid=“+ApiKey;
让数据;
获取(api_url)
.then(res=>res.json())
。然后((结果)=>{
结果。推(结果);
this.setState({//)这是一个更改
isLoaded:是的,
项目:结果
});
},
(错误)=>{
这是我的国家({
isLoaded:是的,
错误
});
}
);
});
}
render(){
const{error,isLoaded,items}=this.state;
如果(错误){
返回错误:{Error.message};
}否则,如果(!已加载){
返回装载。。。;
}否则{
返回(
);
}
}
}
导出默认应用程序;
试试这个
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 self = this,
results = [], responses = [];
// 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 => {
responses.push(res.json());
});
};
Promise.all(responses).then((values) => {
self.setState({
isLoaded: true,
items: results
});
});// this works, because setState is called after before all promises are fulfilled
}
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;
类应用程序扩展了React.Component{
const CityListNames=[“彼得堡”、“曼彻斯特”、“布莱顿”、“利物浦”、“加的夫”];
建造师(道具){
超级(道具);
此.state={
错误:null,
isLoaded:false,
项目:[]
};
}
//在应用程序加载时启动下面的功能
componentDidMount(){
这个。getWeather();
}
//getWeather-进行api调用
getWeather=()=>{
让self=这个,
结果=[],回答=[];
//在此处循环浏览我们的城市列表以收集数据
//然后我们将把它推到this.state.results
CityListNames.forEach(函数(名称){
让api_url=”http://api.openweathermap.org/data/2.5/weather?q=“+name+”,英国&appid=“+ApiKey;
让数据;
//获取api数据
获取(api_url)
。然后(res=>{
responses.push(res.json());
});
};
承诺。所有(响应)。然后((值)=>{
自我状态({
isLoaded:是的,
项目:结果
});
});//这是可行的,因为setState是在所有承诺兑现之前调用的
}
render(){
const{error,isLoaded,items}=this.state;
如果(错误){
返回错误:{Error.message};
}否则,如果(!已加载){
返回装载。。。;
}否则{
返回(
);
}
}
}
导出默认应用程序;
fetch()
是异步的。您在控制台中看到的不是快照。它将表示更新,即使是在日志中也可以。图像和屏幕截图的可能副本可以很好地添加到pos