我正在为我的项目使用react-boilerplate。更改路由器参数时,不会重新渲染组件。路由器看起来像这样。
<switch>
<route exact path="/" render={()><homepage {...this.props}/> } />
<route exact path="/practice-areas" component={PracticeAreasLandingPage}/>
<route path="/practice-areas/:practiceAreasItem" component={PracticeAreas}/>} />
<route component={ notfoundpage } />
</switch>
该组件看起来像这样。
class PracticeArea extends PureComponent {
constructor(props) {
super(props);
}
componentWillMount() {
this.props.onInit();
}
render() {
const pa = this.props.practiceArea;
const randPas = this.props.randPracticeAreas;
....
export function mapDispatchToProps(dispatch) {
return {
onInit: () => {
dispatch(loadPracticeArea());
dispatch(loadRandomPracticeAreas());
}
};
}
const mapStateToProps = createStructuredSelector({
practiceArea: makeSelectPracticeArea(),
loading: makeSelectLoading(),
error: makeSelectError(),
randPracticeAreas: makeSelectRandomPracticeAreas(),
randLoading: makeSelectRandomLoading(),
randError: makeSelectRandomError(),
});
const withConnect = connect(
mapStateToProps,
mapDispatchToProps,
);
const withReducer = injectReducer({
key: 'practiceArea',
reducer
});
const withSaga = injectSaga({
key: 'practiceArea',
saga
});
export default compose(
withReducer,
withSaga,
withConnect,
)(PracticeArea);
当单击具有“ / practice-areas / some-route”之类的路由的链接时,该组件不会更新。
答案 0 :(得分:0)
尝试将PracticeAreas
路线移到PracticeAreasLandingPage
路线之前
<Switch>
<Route exact path="/" render={()><homepage {...this.props}/> } />
<Route path="/practice-areas/:practiceAreasItem" component={PracticeArea} />
<Route path="/practice-areas" component={PracticeAreasLandingPage}/>
<Route component={ NotFoundPage } />
</Switch>
Routes
的顺序在Switch
组件中很重要,因为它会从列表中查找path
满足的url
。
如果您导航到localhost:3000/practice-areas/123
,并且PracticeAreasLandingPage
路线早于PracticeArea
,则您仍然满足PracticeAreasLandingPage
的必要条件,即“ practice-areas
”因此Switch最终会首先渲染该图像。而且由于您已经在开始那条路线上,因此看上去没有任何更新。
交换两条路线的位置将解决此问题,因为现在您告诉Switch
进入列表,并检查url
,localhost:3000/practice-areas/123
是否满足{{ 1}} PracticeArea
首先。