当我第一次尝试加载我的组件时,父状态将完美地传递给子组件。每件事看起来都不错。但是,当我刷新我的页面时,我只是看不到传递给孩子的状态。我只看到孩子的一些静态内容。以下是我的父母:
render(){
const {courses} = this.props;
// 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>
);
}
}
CoursesPage.propTypes = {
courses: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired,
children: PropTypes.object.isRequired
};
function mapStateToProps(state, ownProps){
return {
courses: state.courses
};
}
//mapping all course actions to actions in the props
function mapDispatchToProps(dispatch){
return {
actions: bindActionCreators(courseActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage);
此外,这是我的孩子组成部分:
class CourseDetailsAndList extends React.Component {
constructor(props, context){
super(props, context);
this.state = {
courses: this.props.courses
};
}
render(){
const {courses} = this.props;
return (
<div>
<h1>Courses</h1>
<CourseList courses={this.state.courses}/>
</div>
);
}
}
CourseDetailsAndList.propTypes = {
courses: PropTypes.array.isRequired
};
当我刷新页面时,我看不到孩子传递的课程状态,只看到一个空白的孩子。同样,我在控制台中看到了这个警告,这当然是其中一个原因:
Warning: Failed prop type: The prop `courses` is marked as required in `CourseDetailsAndList`, but its value is `undefined`.
in CourseDetailsAndList (created by RouterContext)
in RouterContext (created by Router)
in Router
in Provider
有人可以告诉我在哪里出错我将状态传递给子组件?为什么警告?
答案 0 :(得分:1)
以下是您使用组件的简化版本尝试完成的工作示例:
https://jsfiddle.net/79qk1r50/2/
class ParentComponent extends React.Component {
render() {
const {parentProp} = this.props;
const childrenWithProps = React.Children.map(this.props.children, function(child) {
return React.cloneElement(child, {parentProp: parentProp});
});
return (
<div>
<h1>ParentComponent</h1>
My parentProp is: {parentProp}
{childrenWithProps}
</div>
);
}
}
class ChildComponent extends React.Component {
render(){
const {parentProp} = this.props;
return (
<div>
<h2>Child Component</h2>
Received from parent: {parentProp}
</div>
);
}
}
React.render(
<ParentComponent parentProp={'foo'}>
<ChildComponent />
<ChildComponent />
</ParentComponent>,
document.getElementById('container'));