如何在React中处理URL参数

时间:2020-03-18 07:56:44

标签: reactjs routing

我有一个使用redux和router的reactJs应用程序。 很抱歉,这个问题更多是关于逻辑而不是代码,但是问题非常狭窄。

我的应用程序中有不同的类别,每个类别都会设置这样的路线:

/:category1/
/:category1/:item1
/:category1/:item1/:scheduling1

有50多种不同的路由,我将它们全部设置在路由器中。

        <PrivateRoute path="/:category1/:item1/:scheduling1" component={SchedulingComponent} />
        <PrivateRoute path="/:category1/:item1" component={ItemComponent} />
        <PrivateRoute path="/:category1" component={CateogryComponent} />

现在,当用户在应用程序中导航时,此功能非常有用。

我面临的问题是当用户重新加载浏览器或直接访问链接时。

由于所有这些路径实际上都是id,因此如果我访问例如/:category1/:item1/:scheduling1

我需要在我的redux存储中调度3个串联的动作

selectCategory
selectItem
selectScheduling

问题是我不知道如何正确处理它。

如果在每个组件的ComponentDidMount中最好地调度一些调用,我会感到困惑(但是当用户导航并且不需要这些调用时也会发生这种情况)

或者在首次加载时是否有方法可以调度所有必要的操作。就像在<app>中制作一个组件一样,它只会在挂载动作时读取并调度该动作(因此只能执行一次)

1 个答案:

答案 0 :(得分:1)

不确定这是否对您有用,但是也许您可以在呈现任何路由内容之前设置redux状态:

function Connected({ Component, ...props }) {
  const dispatch = useDispatch();
  //route changed, dispatch action that will set redux state
  //  assuming this is a sync op
  dispatch({ type: 'PARAM_CHANGE', payload: useParams() });
  //render actual route content, redux state should have been set
  //  with the route parameters
  return <Component {...props} />;
}
const ConnectedRoute = ({
  component: Component,
  ...props
}) => (
  <Route
    {...props}
    render={props => {
      return <Connected Component={Component} {...props} />;
    }}
  />
);

在您的路线中,您可以使用ConnectedRoute:

<Switch>
  <ConnectedRoute
    path="/:id"
    component={SomeContentNeedingIdInReduxState}
  />
  <Route path="/" component={Home} />
</Switch>

此问题是redux存储遵循react-router,并且当react-router更改路由时,路由数据将被复制到存储中。当您在redux开发工具中播放动作时,它将无法实现您的期望。

要让react-router跟随redux存储并通过操作来更改路由,可以使用this package

相关问题