简体   繁体   中英

How to pass object from parent to child class

I am trying to pass an object from the parent to the child class. I make a GET request with axis, where I get the object, then I set the response of the request as this.state.contact in my parent class. Until there all seems good, if I console.log the contact in state it shows up correctly.

The object looks like this when output in the console: {first_name: "Test", last_name: "surname", email: "test@hotmail.com", phone_number: "7228732837", slug: "testhotmailcom"} and if I console log typeof this.state.contact it prints Object

In my child class I just take this.props.contact assign it to this.state.data and console log it in the render method. However, the console prints undefined .

How can I pass this object from the parent class into the child class? I need to set the states in the child class with the props as I will need to render a form with these values.

Here are both classes:

Parent class:

 import React from 'react'; import axios from "axios"; import UpdateContact from './UpdateContact'; export default class Test extends React.Component { state = { contact: '' }; componentDidMount() { const slug = this.props.match.params.slug const url = "http://localhost:3000/api/v1/contacts/" + slug + ".json" axios.get(url) .then( (resp) => { const contact = resp.data.data.attributes this.setState({ contact }) }) .catch( data => { debugger }) } render() { return( <div> <UpdateContact contact={this.state.contact}/> </div> ) } }

Child class:

 import React from 'react'; export default class UpdateContact extends React.Component { constructor(props){ super(props); this.state = { data: this.props.contact } } render(){ return( <div> {console.log(this.state.data)} </div> ) } }

State initialization is run only once when component is mounted and the props.contact is undefined yet. That is why you got undefined in your render.

You need to add componentDidUpdate lifecycle method if you want to update your child component state based on props

  componentDidUpdate(prevProp) {
    if (this.props.contact !== prevProps.contact) {
      this.setState({ data: this.props.contact });
    }
  }

The other thing is that if you don't need to change this.props.contact in your Child component, it's way better to use the prop directly instead of setting state which is not gonna change internally.

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