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

当前回答

要使用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

其他回答

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

如果你需要传递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 )
}

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

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

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

我创建了一个自定义useQuery钩子

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

const useQuery = (): URLSearchParams => {
  return new URLSearchParams(useLocation().search)
}

export default useQuery

使用它作为

const query = useQuery();
const id = query.get("id") as string

就这样发送

history.push({  
 pathname: "/template",
 search: `id=${values.id}`,
});
                  

Pass

history.push({pathname:"/yourroute",state: {_id: "0001", name: "AZ"}})

Read

import React from 'react';

const YourRoute = props=> {
    const { _id, name } = (props.location && props.location.state) || {};
        //_id and name will contain the passed data
     .
     .
     .

}

下面是一个工作示例