【问题标题】:How to split URL in reactjs/nextjs [duplicate]如何在 reactjs/nextjs 中拆分 URL [重复]
【发布时间】:2021-12-13 16:14:27
【问题描述】:

完整的 URL 是 /search-results?query=home+floor&categories=All+Categories。我想像这样把它分成两部分- /search-resultsquery=home+floor&categories=All+Categories。我需要网址的第二部分。如何在 reactjs/nextjs 或 javascript 中执行此操作?

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    使用window.location 来实现:

    var path = window.location.pathname; //should be /search-result
    var queryString = substr(window.location.search, 1); //should be  query=home+floor&categories=All+Categories
    

    编辑:在 Next.js 中,您还可以使用 next/router(在 React 组件中)

    import { useRouter } from 'next/router'
    
    // in component
    const router = useRouter();
    const {pathname, query} = router; //pathname and query are what you are looking for.
    

    【讨论】:

    • 如果我想这样访问,它会返回一个对象,因为查询部分是由查询+类别组成的。我需要访问 getServerSideProps 中的“query=home+floor&categories=All+Categories”部分。这样我就可以将部分附加到 baseUrl 并可以从服务器获取数据。
    • 要在getServerSideProps 中访问,请查看docs for the context argument - context.paramscontext.query 对您来说应该足够了,否则请深入了解context.req
    【解决方案2】:

    您可以简单地在字符串上使用.split() 函数,用“?”字符分割:

    let uri = "/search-results?query=home+floor&categories=All+Categories";
    
    let parts = uri.split("?");
    
    let path = parts[0]; // "/search-results"
    let query = parts[1]; // "query=home+floor&categories=All+Categories"
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

    【讨论】:

      【解决方案3】:

      在 next.js 应用程序中处理位置时,通常最好使用内置的路由器挂钩。 虽然依赖 window 可以用于客户端渲染,但当 next.js 在服务器端渲染某些内容时,您可能会遇到问题。

      import { useRouter } from 'next/router'
      
      function YourComponent() {
        const router = useRouter()
        const parts = router.asPath.split('?')
        // ...
      }
      

      这将在路径变量中为您提供一个数组,其中paths[0]/search-results 并且paths[1] 包含您的查询。 但是,根据您的用例,最好只使用router.query,它会为您提供解析后的查询部分。

      documentation for next/router其实还不错。

      【讨论】:

      • 谢谢。但我需要访问 getServerSideProps 函数中的查询部分。并且那里无法访问钩子。
      • 哦,我明白了。在这种情况下,您真的必须拆分 context.resolvedUrl 或使用 context.query 属性。
      • 谢谢。 Context.resolvedUrl 解决了我的问题。
      猜你喜欢
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      • 2015-05-08
      • 2010-10-01
      • 2014-04-22
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      相关资源
      最近更新 更多