简体   繁体   English

如何在 reactjs/nextjs 中拆分 URL

[英]How to split URL in reactjs/nextjs

The full URl is /search-results?query=home+floor&categories=All+Categories .完整的 URl 是/search-results?query=home+floor&categories=All+Categories I want to split it into two parts like this - /search-results and query=home+floor&categories=All+Categories .我想把它分成两部分 - /search-resultsquery=home+floor&categories=All+Categories I need the second part of the url.我需要网址的第二部分。 How can I do this in reactjs/nextjs or in javascript?我如何在 reactjs/nextjs 或 javascript 中做到这一点?

Usewindow.location to achieve this:使用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

EDIT: In Next.js you can also use next/router (in a React component)编辑:在 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.

You can simple use the .split() function on the string, splitting by the "?"-character:您可以简单地在字符串上使用.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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

When working with locations in next.js applications, it's typically best to use the built-in router hook.在 next.js 应用程序中处理位置时,通常最好使用内置路由器挂钩。 While relying on window would work for client-side rendering, you might run into problems when next.js is rendering something on the server-side.虽然依赖window可以用于客户端渲染,但当 next.js 在服务器端渲染某些东西时,您可能会遇到问题。

import { useRouter } from 'next/router'

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

This would give you an array in the paths variable where paths[0] is /search-results and paths[1] contains your query.这将在路径变量中为您提供一个数组,其中paths[0]/search-results并且paths[1]包含您的查询。 Depending on your use-case it might, however, be better to just use router.query , which gives you the parsed query part.但是,根据您的用例,最好只使用router.query ,它为您提供解析的查询部分。

The documentation for next/router is actually pretty good. next/router文档实际上非常好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM