How to pass async state to child component props?

被刻印的时光 ゝ 提交于 2021-01-22 18:30:31

问题


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;

回答1:


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.




回答2:


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;



回答3:


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
  }, []);


来源:https://stackoverflow.com/questions/56903577/how-to-pass-async-state-to-child-component-props

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!