【问题标题】:React-router: useRouteMatch doesn't return current urlReact-router:useRouteMatch 不返回当前网址
【发布时间】:2021-09-29 13:50:36
【问题描述】:

我正在使用 react-router 和 useRouteMatch 挂钩设置路由。我无法加载组件,因为路径仍然与 URL 不同,但我想知道为什么?因为您可以在浏览器中看到 URL 告诉我它应该匹配,但是当我从 useRouteMatch() 记录 'url' 值时,它仍然落后了一步。

浏览器中的 url 将是“http://localhost:3000/compliance/546545/BeleggersProfiel/Profiel”,但是当我从 useRouteMatch 记录“url”值时,它会显示 http://localhost:3000 /compliance/546545/BeleggersProfiel,所以落后了一步。

如果我在 Route 项中记录下面输入的路径,它是 '/compliance/:compliance_id/BeleggersProfiel/:substep',因此它应该与浏览器中的 URL 匹配,但事实并非如此。有人知道为什么网址不是最新的吗?

export const routes = [
  {
    path: '/:substep',
    Component: SubSteps,
  },
];
function SubWizardRoutes({ steps, wizardRoutes = routes }) {
  const { push, location } = useHistory();
  const { url, path: basePath } = useRouteMatch();

  // when we entered the app and fetched the steps, proceed to the first step
  if (location.pathname === url && steps.length > 0) {
    push(`${url}/${steps[0].name}`);
  }

  return (
    <Switch>
      {wizardRoutes.map((route) => {
        const { Component, path } = route;
        return (
          <Route
            path={`${basePath}${path}`}
            render={({ ...rest }) => {
              return <Component steps={steps} {...rest} />;
            }}
          />
        );
      })}
    </Switch>
  );
}

export default SubWizardRoutes;

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    我认为你不需要useRouteMatchproceed the first step。 请尝试

    const { substep } = useParams()
    const isBeforeFirstStep = substep === undefined && steps.length > 0
    
    if (isBeforeFirstStep) {
      const nextURL = `${url}/${steps[0].name}`
      push(nextURL)
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    相关资源
    最近更新 更多