如何在 React Router Dom 的 useHistory 中发送参数?

Kai*_*ais 15 reactjs react-router-dom react-hooks

我正在使用 React Router hooks 进行导航useHistory

导航: history.push("/home", { update: true });

在家里:我正在尝试获取参数 let {update} = useParams();

update始终未定义。这段代码有什么问题。有什么建议 ?

wen*_*jun 20

history.push()方法中的第二个参数实际上称为位置状态,

history.push(path, [state])
Run Code Online (Sandbox Code Playgroud)

根据您的要求,您可能希望update作为位置状态或查询字符串的一部分进行传递。

history.push({
  pathname: '/home',
  search: '?update=true',  // query string
  state: {  // location state
    update: true, 
  },
}); 
Run Code Online (Sandbox Code Playgroud)

如 React-Router文档所述,您可以通过访问locationprops来访问状态。在您的情况下,要获取 的值update

在类组件上,假设连接到路由器,

this.props.location
Run Code Online (Sandbox Code Playgroud)

对于功能组件,您可以使用useLocation挂钩来访问位置对象。

import { useLocation } from 'react-router-dom';
.
.
const location = useLocation();

console.log(location.state.update)  // for location state
console.log(location.search)  // for query strings;
Run Code Online (Sandbox Code Playgroud)

  • 谢谢 。它有助于。我需要使用 `useLocation` 钩子而不是 `useParams` (4认同)

akh*_*hid 9

这是你可以通过的方式

history.push("/home", { update: true });
Run Code Online (Sandbox Code Playgroud)

如果它是无状态组件,则可以像这样访问。

props.location.state.update;
Run Code Online (Sandbox Code Playgroud)

如果基于类的组件。

this.props.location.update;
Run Code Online (Sandbox Code Playgroud)


Saq*_*y G 5

如果您正在使用 React Hooks,请遵循此方法,因为this.props 仅在 React Class 中可用。

组件一:

import React from 'react'
import { useHistory } from "react-router-dom";

const ComponentOne = () => {
    const history = useHistory();
    const handleSubmit = () => {
        history.push('/component-two',{params:'Hello World'})
    }
    return (
        <div>
            <button onClick={() => {handleSubmit()}}>Fire</button>
        </div>
    )
}
Run Code Online (Sandbox Code Playgroud)

组件二:

import React from 'react'
import { useLocation } from "react-router-dom";

const ComponentTwo = () => {
    const location = useLocation();
    const myparam = location.state.params;
    return (
        <div>
            <p>{myparam}</p>
        </div>
    )
}
Run Code Online (Sandbox Code Playgroud)