我在使用react钩子的reach路由器上遇到了一点问题。我需要在浏览器中捕获路由的参数,我尝试使用web of reach路由器中本地文档的道具来获取路由参数,但这没有给我提供参数,路由是这样的:http://localhost:8080/home?init=true
如何捕获变量"init"?
发布于 2020-05-02 01:22:59
Reach路由器有一个可以使用的useLocation钩子:
import { useLocation } from "@reach/router"
// then
const location = useLocation()在location.search中是搜索字段,包含来自您的URL的所有查询参数(查询字符串)。在您的示例中,/home?init=true将返回location.search: "?init=true",这是一个查询字符串。
您可以使用query-string库(yarn add query-string)来解析以下内容:
import { parse } from "query-string"
// then
const searchParams = parse(location.search)这将为您提供对象{init: "true"},您还可以使用queryString.parse('foo=true', {parseBooleans: true})解析布尔值
所以完整的例子是
import { useLocation } from "@reach/router"
import { parse } from "query-string"
// and
const location = useLocation()
const searchParams = parse(location.search) // => {init: "true"}https://stackoverflow.com/questions/58492797
复制相似问题