2017-06-18 65 views
0

我是Redux的新手,目前使用API​​來獲取數據。我試圖使用React.cloneElement將狀態從父母傳遞給this.props.children。我認爲我在使用React.cloneElement時犯了一個錯誤,因爲當我將它傳遞給cloneElement函數時,調試器顯示的狀態爲空。以下是我的父級渲染方法:React-redux REST API this.state爲空

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> 

    ); 
} 

從控制檯,我可以公平地認爲它正確調用孩子,但在課程中傳遞空值。但是,當我簡單地通過<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

既然你在一個變量傳遞從父類的子類CourseList,你將需要使用props代替

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肯定有效,但我沒有清楚地從文檔中瞭解何時提交this.state vs this.props。另外,如果我的意圖是克隆狀態或將狀態「傳遞」給我的子組件,那麼this.props會在這裏扮演什麼角色? – Omkar

+0

也許這可能是一個更好的方式來區分道具和狀態https://stackoverflow.com/a/27992380/4540216 簡而言之,道具是一個子元件接受的對象,並且狀態在元件中是可變的這可能會觸發重新渲染 – XPLOT1ON

+0

我剛剛編輯了你的代碼(並粘貼在我的答案中),這可能是你想要的,而不是複製對象。 @Omkar – XPLOT1ON