首页 > 解决方案 > 如何从 react-router-dom 索引中获取参数?

问题描述

我需要从 '/:ref' 获取 ref 参数并重定向到家庭路由器 '/home'

const App: FC = () => {
...
  return (
    <IntlProvider locale={language} messages={MESSAGES[language]}>
      <IonApp>
        <IonReactRouter>
          <Toolbar />
          <Menu />
          <IonRouterOutlet id="menuContent">
            <Route path={ROUTES.DASHBOARD} component={Dashboard} exact />
            <Route path={ROUTES.HISTORY} component={HistoryOrders} exact />
            <Route path={ROUTES.HISTORY_ORDER_ID} component={OrderById} exact />
            <Route path={ROUTES.CART} component={Cart} exact />
            <Route path="/:ref" component={IndexRef} exact />
          </IonRouterOutlet>
        </IonReactRouter>
      </IonApp>
    </IntlProvider>
  )
}

import { useParams, useHistory } from 'react-router-dom'
const IndexRef: FC = () => {
  const { ref } = useParams<IIndexRefParams>()
  const history = useHistory()
  const IonStorage = useContext(IonStorageContext)

  useEffect(() => {
    const setRefToStorage = async (shop: string) => {
      await IonStorage.set(SHOP_REF, shop)
    }
    if (ref) {
      setRefToStorage(ref)
      history.push(ROUTES.DASHBOARD)
    }
  }, [])

  return (
    <PageContainer>
      <h1>
        <FormattedMessage id="index.wrongLink" />
      </h1>
    </PageContainer>
  )
}

问题是所有其他路由都匹配“/”。我无法让任何其他路由器收集此“ref”参数,因为指向此路径的重定向链接会创建第三方服务。解决方法是什么?

标签: reactjsreact-routerreact-router-dom

解决方案


推荐阅读