简体   繁体   中英

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. 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.

The componentDidMount lifecycle method is called only once in the starting. Whereas, the componentDidUpdate lifecycle method gets called whenever there is a change in the state of the application. Since api calls are asynchronous, the initChild() function is already called once before the api call's results are passed to the child.

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() {
   console.log(props.data);
   //Update child component state with props.data
}

If you are using functional component, use useEffect

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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