【问题标题】:How to pass data between pages without URL Parameters如何在没有 URL 参数的页面之间传递数据
【发布时间】:2023-05-02 11:11:01
【问题描述】:

我想知道如何使用 ReactRouter 在 Ionic 5 的两个页面之间传递非字符串数据。

我能找到的所有解决方案都使用了 Ionic 和 Angular,或者只是将一个字符串作为 URL 参数传递。

到目前为止,这些是我的组件:

App.tsx

   const App: React.FC = () => {
      return (
        <IonApp>
          <IonReactRouter>
            <IonSplitPane contentId="main">
              <Menu />
              <IonRouterOutlet id="main">
                <Route path="/page/Home" component={Home} exact />
                <Route path="/page/DataEntry" component={DataEntry} exact />
                <Route path="/page/Request" component={Request} exact />
                <Route path="/page/ResultMap" component={ResultMap} exact />
                <Redirect from="/" to="/page/Home" exact />
              </IonRouterOutlet>
            </IonSplitPane>
          </IonReactRouter>
        </IonApp>
      );
    };

这里的第1页收集用户输入数据(字符串、对象、数组),我想在按钮点击时调用路由'/page/ResultMap'并传递数据,以便下一页可以处理:

  <IonGrid>
  <IonRow>
    <IonCol class="ion-text-center">
     <IonButton text-center="ion-text-center" color="primary" size="default" routerLink='/page/ResultMap'>Erkunden!</IonButton> 
    </IonCol>
  </IonRow>
</IonGrid>

第 2 页,应该接收数据:

const ResultMap: React.FC = () => {
  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonButtons slot="start">
            <IonMenuButton />
          </IonButtons>
          <IonTitle>Map</IonTitle>
        </IonToolbar>
      </IonHeader>

      <IonContent fullscreen>
      </IonContent>
    </IonPage>
  );
};

我了解 React 关于 props 和 state 的原理,只是不知道在这种情况下如何将它与 Ionic 结合起来。

感谢您的帮助!

编辑:

按照建议,我像这样更改了 onClick 按钮:

     <IonButton text-center="ion-text-center" color="primary" size="default" onClick={e => {
       e.preventDefault();
       history.push({
         pathname: '/page/ResultMap',
         state: { time: transportTime }
       })}}>

并尝试像这样在 ResultMap 页面上接收数据:

let time = history.location.state.time;

但我得到了错误:

Object is of type 'unknown'.  TS2571

     7 |   let history = useHistory();
     8 | 
  >  9 |   let time = history.location.state.time;
       |              ^

如何在新页面访问传递的对象?

【问题讨论】:

标签: ionic-framework react-router ionic5


【解决方案1】:

至于 react-router 我知道你可以用这个:

history.push({
  pathname: '/template',
  state: { detail: response.data }
})

在这种情况下,您可以在没有 URL 参数的情况下传递数据 也可以使用 history.replace 如果您重定向并希望后退按钮对最终用户正常工作

对于历史,请执行以下操作

let history = useHistory();

Check this link for a great understand how to implement the useHistory type

【讨论】:

  • 感谢您的回答,我用收到的错误更新了我的问题。
  • 尝试添加像这样的泛型类型 const history = useHistory();正如我从我的 IDE 中看到的那样,默认情况下它是未知的泛型类型,这就是您可以更改它的方式。我添加了一个有用的链接,可以帮助你回答我的问题