admin管理员组

文章数量:1336357

I'm new to react and I am trying to fetch data from an API and pass the data to a child ponent. I've passed the data to the state on my parent ponent, however, when I pass it to the child ponent 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});
        });
    }

    ponentDidMount = () => 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]);
    }

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

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

export default Child;

I'm new to react and I am trying to fetch data from an API and pass the data to a child ponent. I've passed the data to the state on my parent ponent, however, when I pass it to the child ponent 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});
        });
    }

    ponentDidMount = () => 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]);
    }

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

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

export default Child;
Share Improve this question asked Jul 5, 2019 at 12:59 SaiSai 8413 gold badges12 silver badges32 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Change the ponentDidMount in the child to ponentDidUpdate.

The ponentDidMount lifecycle method is called only once in the starting. Whereas, the ponentDidUpdate 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]);
        }        
    }

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

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

export default Child;

本文标签: javascriptHow to pass async state to child component propsStack Overflow