2017-06-18 5 views
0

私はReduxを初めて使用しており、現在APIを使用してデータを取得しています。 React.cloneElementを使用して親からthis.props.childrenに状態を渡そうとしています。私は、私がcloneElement関数に渡すときに、デバッガがnullであることを示す状態でReact.cloneElementを使用しているときに間違いを犯していると思います。私の親はrenderメソッドを以下に示します。コンソールからReact-redux REST API this.state is null

render(){ 

    const {courses} = this.state; 
    debugger; 
    let fn = (child) => { 
     return React.cloneElement(child, { 
      courses: courses 
     }); 
    }; 

    let childrenWithProps = React.Children.map(this.props.children, fn); 

    return (
     <div> 
      <div className="container jumbotron jumbotron-fluid"> 
       <h1>CoursesPage</h1> 
       <p>This page adds and lists all the courses</p> 
       <Link to="/courses/courseslist"> 
        <Button color="primary">Course Listing</Button> 
       </Link> 
      </div> 
      {childrenWithProps} 
     </div> 

    ); 
} 

、私はかなりそれが正しく子供たちを呼び出しますが、コースにnull値を渡していると仮定することができます。しかし、私が単に<CourseList courses={courses} />を渡すと、それは正しく状態を仮定します。では、どこが間違っているのですか?

は、私は、コンソールに次のエラーを取得する:

Uncaught TypeError: Cannot read property 'map' of undefined 
at CourseList (courseList.js:20) 
at ReactCompositeComponent.js:305 
at measureLifeCyclePerf (ReactCompositeComponent.js:75) 
at ReactCompositeComponentWrapper._constructComponentWithoutOwner (ReactCompositeComponent.js:304) 
at ReactCompositeComponentWrapper._constructComponent (ReactCompositeComponent.js:279) 
at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:187) 
at Object.mountComponent (ReactReconciler.js:45) 
at ReactDOMComponent.mountChildren (ReactMultiChild.js:236) 
at ReactDOMComponent._createInitialChildren (ReactDOMComponent.js:703) 
at ReactDOMComponent.mountComponent (ReactDOMComponent.js:522) 

..where courseListは、子コンポーネントです。

大変助かりました。

答えて

1

あなたは子クラスに親クラスから変数を渡しているので、あなたが代わりにpropsを使用する必要がありますCourseList

const {courses} = this.props; 

リンクドキュメントComponents and Props

にこれがあなたの代わりに何をしたいかもしれません。

render(){ 
    const {coursesList} = this.props; 

    return (
     <div> 
      <div className="container jumbotron jumbotron-fluid"> 
       <h1>CoursesPage</h1> 
       <p>This page adds and lists all the courses</p> 
       <Link to="/courses/courseslist"> 
        <Button color="primary">Course Listing</Button> 
       </Link> 
      </div> 
      {coursesList} 
     </div> 

    ); 
} 
+0

@ X PLOT1ON確かにうまくいったが、私はこの文書をいつ提出するかについて明確に理解していなかった。また、私の意図が状態を複製すること、または子コンポーネントに状態を渡すことである場合、この.propsはここでどのように再生するのですか? – Omkar

+0

おそらく、これは小道具と州を区別する良い方法かもしれません。https://stackoverflow.com/a/27992380/4540216 簡単に言えば、小道具は、子コンポーネントが受け入れたものと状態がコンポーネント内で可変であるオブジェクトのオブジェクトです再レンダリングを引き起こす可能性があります – XPLOT1ON

+0

私はちょうどあなたのコードを編集し(そして私の答えに貼り付けました)、これはあなたがオブジェクトのコピーを作るのではなく、あなたが望むものかもしれません。 @オマール – XPLOT1ON