Javascript 如何使react.js中的render()等待使用xml中的对象填充我的数组
好吧,我一直在寻找答案,我尝试了所有我遇到的方法,但似乎没有任何效果,所以现在我希望有人来拯救我 我在react中有一个简单的函数,它从xml中获取数据,然后填充一个状态(数组),我希望从中在render()中显示数据。但是,由于render()异步获取数据,因此它似乎在填充列表之前启动。我尝试了多种方法来填充列表、设置超时和/或加载框,但我的数组似乎仍然是未定义的,或者至少对象会 我做错了什么 提前谢谢你的建议。另外,请记住,这不是我第一次填充数组,它只是处于我在本文中留下的状态Javascript 如何使react.js中的render()等待使用xml中的对象填充我的数组,javascript,node.js,reactjs,Javascript,Node.js,Reactjs,好吧,我一直在寻找答案,我尝试了所有我遇到的方法,但似乎没有任何效果,所以现在我希望有人来拯救我 我在react中有一个简单的函数,它从xml中获取数据,然后填充一个状态(数组),我希望从中在render()中显示数据。但是,由于render()异步获取数据,因此它似乎在填充列表之前启动。我尝试了多种方法来填充列表、设置超时和/或加载框,但我的数组似乎仍然是未定义的,或者至少对象会 我做错了什么 提前谢谢你的建议。另外,请记住,这不是我第一次填充数组,它只是处于我在本文中留下的状态 import
import React, { Component } from 'react';
//import './Conditions.css';
class GridConditionsXML extends Component {
constructor(props) {
super(props)
this.state = {
locationArray: ['Visby', 'Tofta', 'Östergarn', 'Fårösund'],
filledArray: ''
}
this.createGrid = this.createGrid.bind(this);
}
componentDidMount = () => {
this.createGrid();
}
createGrid = () => {
const self = this;
const locationArr = self.state.locationArray;
const tempArray = [];
for (let i = 0; i < locationArr.length; i++) {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
const xmlDoc = this.responseXML;
const windSpeed = xmlDoc.getElementsByTagName('windSpeed')[0];
const windspeed = windSpeed.getAttribute('mps');
tempArray.push({
name: locationArr[i],
windspeed: windspeed
})
}
};
xhttp.open("GET", `http://www.yr.no/place/Sweden/Gotland/${locationArr[i]}/forecast_hour_by_hour.xml`, true);
xhttp.send();
}
self.setState({
filledArray: tempArray
})
}
render() {
console.log(this.state.filledArray) // <-- This works, shows me a filled array
console.log(this.state.filledArray[0].name) // <-- This does not work.
return (
<div>
<p className="normal">Name: <span className="fatData">{this.state.filledArray}</span></p>
</div>
)
}
}
export default GridConditionsXML;
import React,{Component}来自'React';
//导入“/Conditions.css”;
类GridConditionsXML扩展组件{
建造师(道具){
超级(道具)
此.state={
位置数组:['Visby','Tofta','Östergarn','Fårösund'],
填充阵列:“”
}
this.createGrid=this.createGrid.bind(this);
}
componentDidMount=()=>{
这是createGrid();
}
createGrid=()=>{
const self=这个;
const locationArr=self.state.locationArray;
常量tempArray=[];
for(设i=0;i console.log(this.state.filledArray)//您可以使用映射并在执行映射后设置状态,而不是for循环。这应该适合您
createGrid = () => {
const self = this;
var flag = 0;
const locationArr = self.state.locationArray;
const tempArray = [];
locationArr.map(function(value, index) {
const xhttp = new XMLHttpRequest();
xhttp.open("GET", `http://www.yr.no/place/Sweden/Gotland/${locationArr[i]}/forecast_hour_by_hour.xml`, true);
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
const xmlDoc = this.responseXML;
const windSpeed = xmlDoc.getElementsByTagName('windSpeed')[0];
const windspeed = windSpeed.getAttribute('mps');
flag++;
tempArray.push({
name: value,
windspeed: windspeed
})
}
if (locationArr.length === flag) {
this.populateArray(tempArray);
}
};
xhttp.send();
});
}
populateArray = tempArray = {
this.setState({
filledArray: tempArray,
filledArrayLoaded: true
});
}
render() {
console.log(this.state.filledArray)
if (this.state.filledArray.length > 0) {
console.log(this.state.filledArray[0].name) ;
}
return (
<div>
{this.state.filledArrayLoaded && ( <p className="normal">Name: <span className="fatData">{this.state.filledArray}</span></p>
</div>)}
)
}
createGrid=()=>{
const self=这个;
var标志=0;
const locationArr=self.state.locationArray;
常量tempArray=[];
locationArr.map(函数(值、索引){
const xhttp=new XMLHttpRequest();
xhttp.open(“GET”`http://www.yr.no/place/Sweden/Gotland/${locationArr[i]}/forecast\u hour\u by\u hour.xml`,true);
xhttp.onreadystatechange=函数(){
if(this.readyState==4&&this.status==200){
const xmlDoc=this.responseXML;
const windSpeed=xmlDoc.getElementsByTagName('windSpeed')[0];
const windspeed=windspeed.getAttribute('mps');
flag++;
tempArray.push({
名称:value,
风速:风速
})
}
if(位置arr.length==标志){
这个.populateArray(临时数组);
}
};
xhttp.send();
});
}
populateArray=tempArray={
这是我的国家({
填充阵列:临时阵列,
filledarayloaded:对
});
}
render(){
console.log(this.state.filledArray)
如果(this.state.filledaray.length>0){
console.log(this.state.filledArray[0].name);
}
返回(
{this.state.filledarayLoaded&(名称:{this.state.filledaray}
)}
)
}
您需要等待这个.state.filledArray[0]
,首先是不带元素的呈现
import React from "react";
class ExampleComponent extends React.PureComponent {
state={ filledArray: [] }
componentDidMount = () => {
this.createGrid();
}
createGrid = () => {
// {...}
// after some processes
this.setState({ filledArray: tempArray })
}
render() {
const { filledArray } = this.state;
return filledArray.length>0?<div>have elements in array</div>:<div>no elements in array</div>
}
}
export default ExampleComponent
从“React”导入React;
类ExampleComponent扩展了React.PureComponent{
状态={Filled阵列:[]}
componentDidMount=()=>{
这是createGrid();
}
createGrid=()=>{
// {...}
//经过一些过程
this.setState({filledaray:tempArray})
}
render(){
const{filledArray}=this.state;
返回filledArray。长度>0?数组中有元素:数组中没有元素
}
}
导出默认示例组件
您可以尝试以下方法
render() {
const { filledArray } = this.state;
if(filledArray.length == locationArray.length){
return(
<div>
<p className="normal">Name: <span className="fatData">{this.state.filledArray}</span></p>
</div>
);
}
else return(
<div> You can display spinner/ Show some waiting msg</div>
);
render(){
const{filledArray}=this.state;
if(filledArray.length==locationArray.length){
返回(
名称:{this.state.filledArray}
);
}
否则返回(
您可以显示微调器/显示一些等待消息
);
}您可以使用async/await并承诺实现Https请求
createGrid = async () => {
const self = this;
const locationArr = self.state.locationArray;
let tempArray = [];
for (let i = 0; i < locationArr.length; i++) {
let response = await new Promise(resolve => {
const xhttp = new XMLHttpRequest();
xhttp.open(
"GET",
`http://www.yr.no/place/Sweden/Gotland/${
locationArr[i]
}/forecast_hour_by_hour.xml`,
true
);
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
const xmlDoc = this.responseXML;
const windSpeed = xmlDoc.getElementsByTagName('windSpeed')[0];
const windspeed = windSpeed.getAttribute('mps');
resolve(windspeed);
}
};
});
tempArray.push({
name: locationArr[i],
windspeed: response
});
}
self.setState({
filledArray: tempArray
});
};
createGrid=async()=>{
const self=这个;
const locationArr=self.state.locationArray;
设tempArray=[];
for(设i=0;i{
const xhttp=new XMLHttpRequest();
xhttp.open(
“得到”,
`http://www.yr.no/place/Sweden/Gotland/${
位置arr[i]
}/按小时预测小时。xml`,
真的
);
xhttp.send();
xhttp.onreadystatechange=函数(){
if(this.readyState==4&&this.status==200){
const xmlDoc=this.responseXML;
const windSpeed=xmlDoc.getElementsByTagName('windSpeed')[0];
const windspeed=windspeed.getAttribute('mps');
解决(风速);
}
};
});
tempArray.push({
名称:locationArr[i],
风速:响应
});
}
自我状态({
填充阵列:tempArray
});
};
我认为您没有做错任何事情,我认为这是React采用异步组件呈现的路线图的一部分。Norm