简体   繁体   中英

React passing data from child -> parent -> another child

I am writing my app with react.js and trying to get a data, which is an array of objects, from a component(P)'s child component(C1), then again pass the data to another child component(C2). However, when I console log the arrived data in (C2), it is weird that it shows the data is there, but when I console log its' property, it says it cannot read property of undefined. The code is below:

class ParentComponent extends Component {

      constructor(props) {
           super(props)
           this.state = {
               photos: []
             }
        }

     myCallback = dataFromChild1 => {
         this.setState({
              photos: dataFromChild1
          })

      render(){
           const { photos } = this.state;

           return (
                 <main>
                    <Child1 callbackFromParent={this.myCallback} />
                    <Child2 photos={photos} />
                 </main>
            )

   }


   class Child1 extends Component {

        constructor(props) {
             super(props)
          }

       componentDidMount() {
            const photos = [{width: '100px'}, {width: '150px'}];
            this.props.callbackFromParent(photos);
         }

       render() {
            return (
                  <main>
                    ...
                  </main>
             )
       }
   }


    function Child2(props) {
          const photos = props.photos;

          console.log(photos)     // > [{..},{..}]

          console.log(photos[0].width)  // > cannot read property 'width' of undefined

          return (
                 <main>
                  ...
                 </main>
           )
    }

This fiddle is what you are searching.

Here's the code:

class ParentComponent extends React.Component {

  constructor(props) {
       super(props);
       this.state = {
           photos: []
         }

    }

  myCallback = dataFromChild1 =>{
     this.setState({
          photos: dataFromChild1
      });
  };

  render() {
       const { photos } = this.state;

       return (
             <main>
                <Child1 callbackFromParent={this.myCallback}/>
                <Child2 photos={photos} />
             </main>
        );
   }

   }


   class Child1 extends React.Component {

        constructor(props) {
             super(props)
          }

       componentDidMount() {
            const photos = [{width: '100px'}, {width: '150px'}];
            this.props.callbackFromParent(photos);
         }

       render() {
            return (
                  <main>
                    ...
                  </main>
             )
       }
   }


    function Child2(props) {
          const photos = props.photos;

          console.log(photos)     // > [{..},{..}]

          console.log(photos[0] ? photos[0].width : undefined)  // > cannot read property 'width' of undefined

          return (
                 <main>
                  ...
                 </main>
           )
    }

ReactDOM.render(
  <ParentComponent name="World" />,
  document.getElementById('container')
);

The setState is async so in the first render your data array is empty.

Change your the Child2 function and test it.i hope the code is usefull for you

function Child2(props) {
    const photos = props.photos; 
    console.log(photos)     // > [{..},{..}]

    if(photos.length){
        console.log(photos[0].width)
    } 

    return (
           <main>
               <p>Or you can use as the following </p>
               <p>{photos.length? photos[0].width : '' }</p>
           </main>
     )
}

Try binding the callback function to the parent.

In the ParentComponent's constructor, write this:

this.myCallback = this.myCallBack.bind(this);

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