React Ionic-菜单如何访问路由器参数?

时间:2020-05-27 15:39:36

标签: reactjs ionic-framework

我从SideMenu Ionic App开始。

我有一个主页,其中包含路线中的“约会”道具

在左侧菜单中,我将放置一个日历,其中将突出显示路线中提供的日期。

如何继续访问菜单中的日期参数?

<IonApp>
        <IonReactRouter>
            <IonSplitPane contentId="main">

                <IonMenu contentId="main" date="????">
                </IonMenu>
                <IonPage id="main">
                    <IonContent>
                        <IonRouterOutlet>
                            <Route
                                path="/Organisation/:date?"
                                render={(props) => (
                                    <Organisation {...props} />
                                )}
                                exact={true}
                            />
                        </IonRouterOutlet>
                    </IonContent>
                </IonPage>
            </IonSplitPane>
        </IonReactRouter>
</IonApp>

我尝试了几种解决方案,但是没人能很好地解决问题。哪个最好?

  • 将所有内容放到IonRouterOutlet下,即,将IonMenu移到Organization组件内。我已经尝试过了,但是每次更改页面时左侧菜单消失1秒(重新加载?)。不好。
  • 将回调函数传递给Organization组件,该组件会将日期发送回IonApp组件。我已经尝试过了,但是会产生无限循环
  • 其他?

谢谢

2 个答案:

答案 0 :(得分:1)

从Ionic提供的侧面菜单模板开始的最佳方法。

这是我在示例应用程序中的结构

      <IonApp>
        <>
          {authInfo?.loggedIn === true ? (
            <IonReactRouter>
              <IonSplitPane contentId="main">
                <Menu />
                <IonRouterOutlet id="main">
                  <Route path="/page/:name" component={Page} exact />
                  <Route path="/tabs" component={TabRootPage} />
                  <Redirect from="/" to="/tabs" exact />
                </IonRouterOutlet>
              </IonSplitPane>
            </IonReactRouter>
          ) : (
            <IonReactRouter>
              <Route
                path="/create-account"
                component={CreateAccountPage}
                exact
              />
              <Route path="/login" component={LoginPage} exact />
              <Redirect from="/" to="/login" exact />
            </IonReactRouter>
          )}
        </>
      </IonApp>

我正在使用反应上下文获取一些状态信息,这些状态信息存储在我的AuthProvider

ReactDOM.render(
  <AuthProvider>
    <App />
  </AuthProvider>,
  document.getElementById("root")
);

然后您可以在Menu中从上下文中获取数据,而无需传递参数。

示例:Video and Blog about Managing State in Ionic React Applications

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

答案 1 :(得分:0)

IonReactRouter在幕后使用React Router,因此一定要参考其文档以了解更多信息。


您可以通过<IonReactRouter/>钩子访问useParams中任何地方的url参数。
-https://reacttraining.com/react-router/web/api/Hooks/useparams

将其添加到您的<IonMenu/>组件定义中

const IonMenu = () => {
  let { date } = useParams(); // here is your date

  return <>...</>
}

在需要参数的任何地方使用此钩子。这样,您可以避免prop drilling,即。需要将道具传递到遥远的地方。