React Router接收到匹配参数,但不更新组件

时间:2019-06-10 22:30:52

标签: reactjs redux react-router redux-saga reselect

我正在为我的项目使用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”之类的路由的链接时,该组件不会更新。

1 个答案:

答案 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进入列表,并检查urllocalhost:3000/practice-areas/123是否满足{{ 1}} PracticeArea首先。