首页 > 解决方案 > 如何让 react.js 中的 render() 等待我的数组填充来自 xml 的对象

问题描述

好吧,所以我一直在寻找答案,并尝试了我遇到的一切,但似乎没有任何效果,所以现在我希望有人能来拯救我。

我有一个简单的反应函数,它从 xml 中获取数据,然后填充一个状态(数组),我想在我的 render() 中显示数据。但是,由于它获取数据异步,因此 render() 似乎在填充列表之前触发。我尝试了多种方法来填充列表、设置超时和/或加载框,但我的数组似乎仍然未定义,或者至少对象会出现。

我在这里做错了什么?

提前感谢您提供有用的建议。另外,请记住,这不是我填充数组的第一种方法,它只是处于我为这篇文章留下的状态。

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; 

标签: javascriptnode.jsreactjs

解决方案


您需要等待, for this.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

推荐阅读