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

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

当前回答

For the earlier versions: history.push('/[pathToSomeWhere]', yourData); And get the data in the related component just like below: this.props.location.state // it is equal to yourData For the newer versions the above way works well but there is a new way: history.push({ pathname: '/[pathToSomeWhere]', state: yourData, }); And get the data in the related component just like below: Class Component this.props.location.state; // it is equal to yourData Function Component const location = useLocation(); location.state; // it is equal to yourData


有时需要使用Link或NavLink组件,而不是使用历史记录。推动作用。你可以用下面的like:

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

提示:状态键名称应在最新版本中使用。

其他回答

带有钩子的React TypeScript

来自班级

  this.history.push({
      pathname: "/unauthorized",
      state: { message: "Hello" },
    });

未经授权的功能组件

interface IState {
  message?: string;
}

export default function UnAuthorized() {
  const location = useLocation();
  const message = (location.state as IState).message;

  return (
    <div className="jumbotron">
      <h6>{message}</h6>
    </div>
  );
}

添加信息以获取查询参数。

const queryParams = new URLSearchParams(this.props.location.search);
console.log('assuming query param is id', queryParams.get('id');

有关URLSearchParams的更多信息,请查看此链接 URLSearchParams

你可以用,

this.props.history。Push ("/template",{…响应}) 或 this.props.history。推送("/template", {response: response})

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

Const state = this.props.location.state

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

扩展解决方案(由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]);

};

没有必要与throuter一起使用。这对我来说很管用:

在父页面中,

<BrowserRouter>
   <Switch>
        <Route path="/routeA" render={(props)=> (
          <ComponentA {...props} propDummy={50} />
        )} />

        <Route path="/routeB" render={(props)=> (
          <ComponentB {...props} propWhatever={100} />
          )} /> 
      </Switch>
</BrowserRouter>

然后在ComponentA或ComponentB中进行访问

this.props.history

对象,包括this.props.history.push方法。