javascript - 如何将异步状态传递给子组件 Prop ?

标签 javascript reactjs asynchronous react-props react-state

我是 React 新手,我正在尝试从 API 获取数据并将数据传递给子组件。我已经将数据传递给父组件上的状态,但是,当我将它作为 props 传递给子组件时,它会记录为一个空数组。我确定我忽略了一些简单的东西,但我不知道是什么,我的代码在下面

父组件

import React, {Component} from 'react';
import Child from '../src/child';
import './App.css';

class App extends Component {
    constructor(props) {
        super(props);

        this.state = {
          properties: []
        }
    }

    getData = () => {
        fetch('url')
        .then(response => {
            return response.text()
        })
        .then(xml => {
            return new DOMParser().parseFromString(xml, "application/xml")
        })
        .then(data => {
            const propList = data.getElementsByTagName("propertyname");
            const latitude = data.getElementsByTagName("latitude");
            const longitude = data.getElementsByTagName("longitude");

            var allProps = [];

            for (let i=0; i<propList.length; i++) { 
                allProps.push({
                    name: propList[i].textContent,
                    lat: parseFloat(latitude[i].textContent), 
                    lng: parseFloat(longitude[i].textContent)
                });
            }

            this.setState({properties: allProps});
        });
    }

    componentDidMount = () => this.getData();

    render () {
        return (
            <div>
                <Child data={this.state.properties} />
            </div>
        )
    }
}

export default App;

子组件

import React, {Component} from 'react';

class Child extends Component {
    initChild = () => {
        console.log(this.props.data); // returns empty array

        const properties = this.props.data.map(property => [property.name, property.lat, property.lng]);
    }

    componentDidMount = () => this.initChild();

    render () {
        return (
            <div>Test</div>
        )
    }
}

export default Child;

最佳答案

将子组件中的 componentDidMount 更改为 componentDidUpdate。

componentDidMount 生命周期方法在开始时只调用一次。然而,只要应用程序的状态发生变化,就会调用 componentDidUpdate 生命周期方法。由于 api 调用是异步的,因此在将 api 调用的结果传递给子项之前,已经调用了 initChild() 函数。

关于javascript - 如何将异步状态传递给子组件 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56903577/

相关文章:

c# - 用于制表符丢失焦点事件的 Javascript

javascript - 从 firefox 扩展的数据目录播放音频

node.js - 如何使用 React Router 从 React.js 的子路径修复错误的代理重定向?

javascript - 错误: Trying to print out array elements in React Function Component?

c# - Windows 窗体应用程序中的异步显示

jquery - 使用 jQuery 调用 Controller 操作

design-patterns - 异步观察者模式

javascript - 使用 Google 表格中的数据在 Google Apps 脚本中自动完成

javascript - 尝试将 jquery 设置为在调整大小后触发一次

reactjs - navigation.goback() 缺少数据