I'm new to React, React Router (v4) and Redux. I'm trying to access a URL parameter from mapStateToProps(state, ownProps)
by accessing ownProps.match.params.id
but the params
array is always empty. I've used the debugger to inspect ownProps and the id
parameter that should be passed isn't anywhere in ownProps
.
Here is a snippet from my routes:
<Switch>
<Route exact path='/' component={HomePage} />
<Route path='/about' component={AboutPage} />
<Route path='/course' component={ManageCoursePage} />
<Route path='/course/:id' component={ManageCoursePage} />
<Route path='/courses' component={CoursesPage} />
</Switch>
Here is the relevant code from ManageCoursePage.js
:
class ManageCoursePage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
course: Object.assign({}, props.course),
errors: {},
};
}
}
function mapStateToProps(state, ownProps) {
const courseId = ownProps.match.params.id;
...
}
export default connect(mapStateToProps, mapDispatchToProps)(ManageCoursePage);
You have to flip the order of the following routes or set the
exact
property to the first route./course
matches before/course/:id
thats whyManageCoursePage
is called without the id param. if you only want to match/course
in your first route and not/course/123
you can set theexact
property.