如何在 react-router v4 中使用 history.push/Link/Redirect 传递参数?

IT技术 reactjs react-router
2021-05-09 05:41:42

我们如何this.props.history.push('/page')在 React-Router v4 中传递参数

.then(response => {
       var r = this;
        if (response.status >= 200 && response.status < 300) {
             r.props.history.push('/template');
          });
4个回答

首先,你不需要这样做,var r = this;因为 thisif statement指的是回调本身的上下文,因为你使用箭头函数指的是 React 组件上下文。

根据文档:

历史对象通常具有以下属性和方法:

  • length - (number) 历史堆栈中的条目数
  • action - (字符串)当前操作(PUSH、REPLACE 或 POP)
  • 位置 - (对象)当前位置。可能具有以下属性:

    • 路径名 - (字符串)URL 的路径
    • search - (string) URL 查询字符串
    • hash - (string) URL 散列片段
    • state - (字符串)特定于位置的状态,当此位置被推送到堆栈时提供给例如 push(path, state)。仅在浏览器和内存历史记录中可用。
  • push(path, [state]) - (function) 将一个新条目推入历史堆栈
  • replace(path, [state]) - (函数)替换历史堆栈中的当前条目
  • go(n) - (function) 将历史堆栈中的指针移动 n 个条目
  • goBack() - (function) 等价于 go(-1)
  • goForward() - (function) 等价于 go(1)
  • 阻止(提示)-(功能)阻止导航

因此,在导航时,您可以将props传递给历史对象,例如

this.props.history.push({
  pathname: '/template',
  search: '?query=abc',
  state: { detail: response.data }
})

或类似的Link组件或Redirect组件

<Link to={{
      pathname: '/template',
      search: '?query=abc',
      state: { detail: response.data }
    }}> My Link </Link>

然后在使用/template路由呈现的组件中,您可以访问传递的props

this.props.location.state.detail

还要记住,当使用 props 中的历史或位置对象时,您需要将组件与withRouter.

根据文档:

带路由器

您可以<Route>'s通过withRouter高阶组件访问历史对象的属性和最接近的 匹配项withRouter 每次使用与<Route>render相同的 props 更改路由时,都会重新渲染其组件props: { match, location, history }

扩展解决方案(由 Shubham Khatri 建议)以与 React 挂钩(16.8 及更高版本)一起使用:

package.json (always worth updating to latest packages)

{
     ...

     "react": "^16.12.0",
     "react-router-dom": "^5.1.2",

     ...
}

使用历史推送传递参数:

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

const FirstPage = props => {
    let history = useHistory();

    const someEventHandler = event => {
       history.push({
           pathname: '/secondpage',
           search: '?query=abc',
           state: { detail: 'some_value' }
       });
    };

};

export default FirstPage;


使用来自“react-router-dom”的 useLocation 访问传递的参数:

import { useEffect } from "react";
import { useLocation } from "react-router-dom";

const SecondPage = props => {
    const location = useLocation();

    useEffect(() => {
       console.log(location.pathname); // result: '/secondpage'
       console.log(location.search); // result: '?query=abc'
       console.log(location.state.detail); // result: 'some_value'
    }, [location]);

};

  1. 对于早期版本:

    history.push('/[pathToSomeWhere]', yourData);
    

    并在相关组件中获取数据,如下所示:

    this.props.location.state // it is equal to yourData
    
  2. 对于较新的版本,上述方法效果很好,但有一种新方法:

    history.push({
      pathname: '/[pathToSomeWhere]',
      state: yourData,
    });
    

    并在相关组件中获取数据,如下所示:

    • 类组件

      this.props.location.state; // it is equal to yourData
      
    • 功能组件

      const location = useLocation();
      location.state; // it is equal to yourData
      

有时需要使用LinkNavLink组件而不是使用history.push功能。你可以像下面这样使用:

<Link
  to={{
    pathname: '/[pathToSomeWhere]',
    state: yourData
  }}
> 
  ...
</Link>

提示state应在最新版本中使用密钥名称。

您可以使用,

this.props.history.push("/template", { ...response }) 或者 this.props.history.push("/template", { response: response })

然后您可以/template通过以下代码访问来自组件的解析数据

const state = this.props.location.state

阅读有关 React会话历史管理的更多信息