如何跨页面传递数据并将输入附加到数组?(离子+反应)



我正在尝试编写一个移动应用程序,其中涉及测验/问卷方面,用户通过输入他们的选择和路由到下一页并输入他们的下一个选择(这种情况大约发生5次,有5个问题)-然后我必须根据他们的选择显示最终结果。

我认为最简单的方法是使用一个空数组,并将用户的输入附加为数组元素,然后使用'if'语句创建我自己的算法来显示结果。

我不知道如何将数据传递到下一页并将该值附加到数组中。

请帮助哈哈,我正在努力与离子反应!!

App.tsx中的路由代码:

      <Route exact path = "/question1" component = {Question1}/>
      <Route exact path = "/question2" component = {Question2}/>
      <Route exact path = "/question3" component = {Question3}/>
      <Route exact path = "/question4" component = {Question4}/>
      <Route exact path = "/question5" component = {Question5}/>

提问组(Question1.tsx):

  const [selected, setSelected] = useState<string>();
  
    return ( 
    <IonPage>
       <IonContent fullscreen>           
          <div className="Question3">
                How often do you work out? 
            </div>
            <IonList>
            <IonRadioGroup value={selected} onIonChange={e => setSelected(e.detail.value)}>
            <IonItem>
              <IonLabel>Daily</IonLabel>
              <IonRadio slot="start" value="1" />
            </IonItem>

Question1.tsx中的下一个按钮:

<div className = "nextBttn">
  <IonCol>
     <IonButton size="small" routerLink = "/Question2">Next</IonButton>
   </IonCol>
</div>

Ionic React 5 + 6版本都使用了React Router 5,但是Ionic Router增加了一些与后退按钮相关的额外处理,这使得事情变得有点复杂。

使用查询字符串

不是将您的答案存储为react-router参数,而是将它们存储为查询字符串;这样解析起来会容易得多。

下面是我如何在Ionic React应用程序中处理一些简单的重定向的例子。你可以使用相同的方法

组件,解析查询字符串

import queryString from 'query-string';
  const parsedQueryString = queryString.parse(window.location.search);
  const { dest } = parsedQueryString;
  // Now we can do whatever we want with the redirect destination.

组件,该组件设置包含查询字符串的链接

let dest;
if (someBooleanValue) {
  dest = '?dest=page1';
} else {
  dest = '?dest=page2';
}
return (
  <IonButton
    routerLink={`${routeVariable}${dest}`}
      >
        Go Somewhere
  </IonButton>

备选解决方案:

您还可以使用useState()useReducer()创建上下文并将答案存储在那里。但是设置起来要复杂一些。

最新更新