2017-06-18 45 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