0
當我嘗試加載我的組件首次,雙親狀態是完全傳遞給孩子。每件事都看起來不錯。但是,當我刷新我的頁面時,我無法看到傳遞給子項的狀態。我只是看到一些來自孩子的靜態內容。以下是我的父母:刷新頁面反應父狀態不會傳遞到子狀態
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
是否有人可以告訴我,我錯了我傳遞的狀態到子組件?爲什麼警告?
你已經有了''中CoursesPage.propTypes' courses'註釋掉。 你確定你正在爲'CoursesPage.courses'傳遞一個有效的值嗎? – Scott
@斯科特是的,我傳遞了正確的價值。按鈕onclick事件首先正確拉取數據。當我刷新頁面時,它只顯示孩子而不顯示數據。這意味着GET數據的操作不會觸發。但我不明白我出錯的地方。我是否也需要在子組件中使用mapDispatchToProps? – Omkar
'mapDispatchToProps'是一個redux幫助器方法,因此在這個實例中是否使用該方法將取決於您是否在此應用中使用了redux。 在你上面分享的代碼中,你只包含了'CoursesPage'組件的'render'方法。你能分享整個組件嗎? – Scott