我是Redux的新手,目前正在使用API来获取数据。我正在尝试使用React.cloneElement将状态从我的父母传递给this.props.children。我认为当我使用React.cloneElement时我犯了一个错误,因为当我将它传递给cloneElement函数时,调试器显示的状态为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>
);
}
从控制台,我可以合理地假设它正确地调用了孩子,但是在课程中传递了空值。但是,当我简单地通过
<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是子组件。
非常感谢帮助。
最佳答案
由于您要将变量从Parent类传递给子类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>
);
}