【问题标题】:query string react-router path查询字符串反应路由器路径
【发布时间】:2017-06-26 16:44:57
【问题描述】:

我正在使用 react-router 3.0.2 并尝试使用查询字符串配置路由器路径。这就是我配置路由器的方式:

<Router history={browserHistory}>
                <Route path="abc/login.do" component={LoginComponent}/>
                <Route path="abc/publicLoginID.do?phase=def" component={VerifyComponent} />
                <Route path="abc/publicLoginID.do?phase=ghi" component={ImageComponent}/>
                <Route path="*" component={LoginComponent}/>
</Router>

我知道这不是在“路线”中指定查询字符串 (?) 的正确方法。如何确保当用户在 url 中输入“http://localhost:3000/abc/publicLoginID.do?phase=def”时,会显示“VerifyComponent”,当他在 url 中输入“http://localhost:3000/abc/publicLoginID.do?phase=ghi”时,会显示“ImageComponent”。

我确实在这里检查了一些案例:react-router match query stringQuerystring in react-router,但无法弄清楚如何使其工作。

【问题讨论】:

  • 您可以编写一个包装器组件,它将根据查询参数切换要呈现的内容

标签: reactjs react-router query-string


【解决方案1】:

您可以编写一个包装器组件,它将根据查询参数切换要呈现的内容

<Router history={browserHistory}>
   <Route path="abc/login.do" component={LoginComponent}/>
   <Route path="abc/publicLoginID.do" component={WrapperComponent} />
   <Route path="*" component={LoginComponent}/>
</Router>

//WrapperComponent

WrapperComponent = (props) => {
   if (props.location.query.phase==="def"){return <VerifyComponent {...props}/>}
   if (props.location.query.phase==="ghi"){return <ImageComponent {...props}/>}
}

【讨论】:

  • 谢谢@UG_,它成功了。我唯一担心的是,如果我们有一个像 &lt;Router history={browserHistory}&gt; &lt;Route path="abc/login.do?phase=jkl" component={RandomComponent}/&gt; &lt;Route path="abc/login.do?phase=mno" component={LoginComponent}/&gt; &lt;Route path="abc/publicLoginID.do?phase=def" component={VerifyComponent} /&gt; &lt;Route path="abc/publicLoginID.do?phase=ghi" component={ImageComponent}/&gt; &lt;Route path="*" component={LoginComponent}/&gt; &lt;/Router&gt; 这样的路由器,我们是否需要 2 个包装器组件,一个用于 login.do,另一个用于 publicLoginID.do?
  • 是的,理想情况下我想分别处理两条路线。
  • 你也可以把它全部放在一个组件中,根据路由进行切换,但这违背了使用react-router的目的
猜你喜欢
  • 2022-01-16
  • 2016-07-06
  • 2022-01-10
  • 2017-05-07
  • 2017-08-14
  • 1970-01-01
  • 2022-01-17
  • 2016-01-01
相关资源
最近更新 更多