【问题标题】:React router, inferred query string反应路由器,推断查询字符串
【发布时间】:2022-01-16 23:12:29
【问题描述】:

我确实意识到这可能是一种不好的做法,但我需要以这种方式根据用户的电子邮件重定向用户:

/chat?user={emailAddress}

确切的路径应该是什么样子,以便我可以在 chatRenderer 中将 emailAddress 作为道具访问? URL 中必须有 name 查询。

   <Route
     exact
     path={`/chat?user=???`}
     render={this.chatRenderer}
   />

【问题讨论】:

  • 电子邮件地址中允许使用逗号、点和其他一些字符,但必须在 URL 中进行转义。因此,您需要转义(然后,取消转义)电子邮件地址。 encodeURIComponentdecodeURIComponent 应该可以满足您的需求。

标签: reactjs react-router


【解决方案1】:

react-router-dom 只关心匹配 URL 的路径部分。

更改 Route 以匹配没有查询字符串的 URL:

<Route
  path="/chat"
  render={this.chatRenderer}
/>

在路由组件中,从 location 对象访问 queryString searchlocationprops 上可用,如果由rendercomponent 属性的Route 渲染,或者可以通过useLocation 钩子访问。

const { search } = location;

...

const searchParams = new URLSearchParams(search);
const userEmail = searchParams.get('user');

// apply logic against userEmail value

【讨论】:

    【解决方案2】:

    App.js

    <Route
         exact
         path="/chat"
         component={UserChatPage}
       />
    

    首页

    import { useHistory } from 'react-router-dom';
    
    function MyHomePage (){
    
    const history = useHistory()
    
    const redirect = ()=> history.push(`/chat?user=${email}`);
    

    用户聊天页面

    var url_string = window.location.href
    var url = new URL(url_string);
    var user = url.searchParams.get("user");
    

    【讨论】:

      猜你喜欢
      • 2017-06-26
      • 2016-07-06
      • 2022-01-10
      • 2017-05-07
      • 2017-08-14
      • 2016-01-01
      • 2018-08-25
      • 2015-04-12
      • 2020-10-15
      相关资源
      最近更新 更多