我正在将Jhipster 6.7.0
与React前端一起使用。生成的代码使用版本5.1.2
中的react-router-dom并创建了以下组件:
routes.tsx:
const Routes = () => (
<div className="view-routes">
<Switch>
<ErrorBoundaryRoute path="/login" component={Login} />
<ErrorBoundaryRoute path="/logout" component={Logout} />
...
<ErrorBoundaryRoute path="/" component={Entities} />
<ErrorBoundaryRoute component={PageNotFound} />
</Switch>
</div>
);
实体本身具有嵌套路线:
const Routes = ({ match }) => (
<div>
<Switch>
{/* prettier-ignore */}
<ErrorBoundaryRoute path={`${match.url}a`} component={A} />
<ErrorBoundaryRoute path={`${match.url}b`} component={B} />
...
{/* jhipster-needle-add-route-path - JHipster will add routes here */}
</Switch>
</div>
);
具体实体组件又具有子路由: 实体B的index.tsx:
const Routes = ({ match }) => (
<>
<Switch>
...
<ErrorBoundaryRoute exact path={`${match.url}/explore`} component={BExplore} />
<ErrorBoundaryRoute exact path={`${match.url}/:id`} component={BDetail} />
...
</Switch>
</>
);
为完整起见,此处生成的ErrorBoundaryRoute
export const ErrorBoundaryRoute = ({ component: Component, ...rest }: RouteProps) => {
const encloseInErrorBoundary = props => (
<ErrorBoundary>
<Component {...props} />
</ErrorBoundary>
);
if (!Component) throw new Error(`A component needs to be specified for path ${(rest as any).path}`);
return <Route {...rest} render={encloseInErrorBoundary} />;
};
由于我的问题:
导航到实体详细信息页面时,BDetail's
渲染方法的调用时间为 4 次。我很新来做出反应,不明白为什么。根据我的理解,当不通过Route渲染传递函数时,像render={() => someComponents}
这样的react应该认识到函数没有改变并且不应该在组件上调用render。我就是这么想的,ErrorBoundaryRoute
就是这样。那么为什么为什么多次调用render方法呢?
要正确渲染我的明细实体,我需要将匹配道具的ID与在redux存储中保存的当前实体的ID进行比较,如下所示:
export const BDetail= (props: IBDetailProps) => {
useEffect(() => {
props.getEntity(props.match.params.id);
}, []);
const { bEntity, hasBs, loading } = props;
return (
<>
{bEntity && bEntity.name && bdEntity.id.toString() === props.match.params.id? (
...
);
};
但这不应该是正常的工作流程,对吗?
此外,我无法在props.history.listen
上添加历史记录更改侦听器,因为单个历史记录更改还会多次调用此侦听器。要解决此问题,我需要使用useLocation
中的react-router-dom
钩子。