简体   繁体   English

如何将异步状态传递给子组件道具?

[英]How to pass async state to child component props?

I'm new to react and I am trying to fetch data from an API and pass the data to a child component.我是新手,我正在尝试从 API 获取数据并将数据传递给子组件。 I've passed the data to the state on my parent component, however, when I pass it to the child component as props it logs as an empty array.我已将数据传递给父组件上的状态,但是,当我将其作为道具传递给子组件时,它会记录为一个空数组。 I'm sure there is something simple I am overlooking but I don't know what, my code is below我确定我忽略了一些简单的东西,但我不知道是什么,我的代码在下面

PARENT COMPONENT父组件

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;

CHILD COMPONENT子组件

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;

Change the componentDidMount in the child to componentDidUpdate.将 child 中的 componentDidMount 更改为 componentDidUpdate。

The componentDidMount lifecycle method is called only once in the starting. componentDidMount 生命周期方法在开始时只调用一次。 Whereas, the componentDidUpdate lifecycle method gets called whenever there is a change in the state of the application.而只要应用程序的状态发生变化,就会调用 componentDidUpdate 生命周期方法。 Since api calls are asynchronous, the initChild() function is already called once before the api call's results are passed to the child.由于 api 调用是异步的,initChild() 函数在 api 调用的结果传递给子进程之前已经调用了一次。

You can use conditional rendering您可以使用条件渲染

 import React, {Component} from 'react'; class Child extends Component { initChild = () => { if(this.props.data){ const properties = this.props.data.map(property => [property.name, property.lat, property.lng]); } } componentDidMount = () => this.initChild(); render () { return ( <div>Test</div> ) } } export default Child;

If you are using Class based component, use componentDidUpdate method如果您使用的是基于类的组件,请使用 componentDidUpdate 方法

componentDidUpdate() {
   console.log(props.data);
   //Update child component state with props.data
}

If you are using functional component, use useEffect如果您正在使用功能组件,请使用 useEffect

useEffect(() => {
    console.log(props.data);
   //Update child component state with props.data
  }, []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM