我们如何在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');
          });

当前回答

没有必要与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方法。

其他回答

要使用React 16.8+(带hooks),您可以使用这种方式

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

export default function SomeFunctionalComponent() {
let history = useHistory(); // should be called inside react component

const handleClickButton = () => {    
"funcionAPICALL"
       .then(response => {
             if (response.status >= 200 && response.status < 300) {
                 history.push('/template');
              });
}

return ( <div> Some component stuff 
    <p>To make API POST request and redirect to "/template" click a button API CALL</p>
    <button onClick={handleClickButton}>API CALL<button>
</div>)
} 

来源这里阅读更多https://reacttraining.com/react-router/web/example/auth-workflow

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

};

您可以使用location将状态发送到其他组件,就像这样

在源组件中

this.props.history.push(pathComponent, sendState);

pathComponent是接收状态的目标组件

在目标组件中 如果您使用类组件,您可以像这样接收状态

Javascript版本

constructor(props) {
  this.state = this.props.location.state
}

打印稿版本

constructor(props: {}) {
  const receiveState = this.props.location.state as StateType // you must parse into your state interface or type
  this.state = receiveState
}

奖金

如果你想重置收到的状态。使用历史记录替换位置,像这样

this.props.history({pathName: currentPath, state: resetState})

“currentPath”为目标组件路径 resetState是你想要的新值状态

如果你需要传递URL参数

Tyler McGinnis在他的网站上有一个很好的解释,链接到这个帖子

下面是代码示例:

关于历史。将组件: this.props.history.push(“/ home: $ {this.state.userID}”) 在路由器组件上定义路由: <路由路径='/home:myKey'组件={home} /> Home组件:

componentDidMount(){
    const { myKey } = this.props.match.params
    console.log(myKey )
}

带有钩子的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>
  );
}