Реагировать на передачу данных от потомка -> родитель -> другой потомок - PullRequest
0 голосов
/ 28 июня 2018

Я пишу свое приложение сact.js и пытаюсь получить данные, которые являются массивом объектов, из дочернего компонента компонента (P) (C1), а затем снова передать данные другому дочернему компоненту ( С2). Однако, когда я консоль регистрирую поступившие данные в (C2), странно, что он показывает, что данные есть, но когда я консоль регистрирую их свойство, он говорит, что не может прочитать свойство undefined. Код ниже:

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>
           )
    }

Ответы [ 3 ]

0 голосов
/ 28 июня 2018

Это скрипка - это то, что вы ищете.

Вот код:

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')
);

setState является асинхронным, поэтому при первом рендеринге ваш массив данных пуст.

0 голосов
/ 28 июня 2018

Измените функцию Child2 и проверьте ее. Надеюсь, код будет вам полезен

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>
     )
}
0 голосов
/ 28 июня 2018

Попробуйте связать функцию обратного вызова с родителем.

В конструкторе ParentComponent напишите это:

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