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

当前回答

首先,你不需要var r = this;就像if语句中引用回调本身的上下文一样,因为你使用的是箭头函数,所以它引用的是React组件上下文。

根据文件:

history objects typically have the following properties and methods: length - (number) The number of entries in the history stack action - (string) The current action (PUSH, REPLACE, or POP) location - (object) The current location. May have the following properties: pathname - (string) The path of the URL search - (string) The URL query string hash - (string) The URL hash fragment state - (string) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history. push(path, [state]) - (function) Pushes a new entry onto the history stack replace(path, [state]) - (function) Replaces the current entry on the history stack go(n) - (function) Moves the pointer in the history stack by n entries goBack() - (function) Equivalent to go(-1) goForward() - (function) Equivalent to go(1) block(prompt) - (function) Prevents navigation

在导航时,你可以将道具传递给历史对象,比如

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

或类似的链接组件或重定向组件

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

然后在使用/template route渲染的组件中,你可以访问传递的道具

this.props.location.state.detail

还要记住,当使用来自道具的历史记录或位置对象时,您需要将组件与throuter连接起来。

根据文档:

withRouter 您可以访问历史对象的属性和最接近的属性 <路由>的匹配通过withRouter高阶组件。withRouter 将重新渲染它的组件时,每次路由改变 与<Route>渲染道具相同:{match, location, history}。

其他回答

首先,你不需要var r = this;就像if语句中引用回调本身的上下文一样,因为你使用的是箭头函数,所以它引用的是React组件上下文。

根据文件:

history objects typically have the following properties and methods: length - (number) The number of entries in the history stack action - (string) The current action (PUSH, REPLACE, or POP) location - (object) The current location. May have the following properties: pathname - (string) The path of the URL search - (string) The URL query string hash - (string) The URL hash fragment state - (string) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history. push(path, [state]) - (function) Pushes a new entry onto the history stack replace(path, [state]) - (function) Replaces the current entry on the history stack go(n) - (function) Moves the pointer in the history stack by n entries goBack() - (function) Equivalent to go(-1) goForward() - (function) Equivalent to go(1) block(prompt) - (function) Prevents navigation

在导航时,你可以将道具传递给历史对象,比如

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

或类似的链接组件或重定向组件

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

然后在使用/template route渲染的组件中,你可以访问传递的道具

this.props.location.state.detail

还要记住,当使用来自道具的历史记录或位置对象时,您需要将组件与throuter连接起来。

根据文档:

withRouter 您可以访问历史对象的属性和最接近的属性 <路由>的匹配通过withRouter高阶组件。withRouter 将重新渲染它的组件时,每次路由改变 与<Route>渲染道具相同:{match, location, history}。

要使用React 16.8(带hooks)功能组件,您可以使用这种方式 我们发送PhoneNumber到Next Page Login.js

    import { useHistory } from 'react-router-dom';
    const history = useHistory();
        const handleOtpVerify=(phoneNumber)=>
          {
               history.push("/OtpVerifiy",{mobNo:phoneNumber})
          } 

<button onClick={handleOtpVerify}> Submit </button>

OtpVerify.js

    import  useLocation  from 'react-router-dom';
    const [phoneNumber, setphoneNumber] = useState("")
        useEffect(() => {
                setphoneNumber(location.state.mobNo)
            }, [location]);
    return (
    <p>We have sent Verification Code to your</p>
    <h1>{phoneNumber}</h1>
    )

React路由器dom版本6.2.1 useNavigate()已弃用

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

 const navigate = useNavigate()
 
 onClick={() => { navigate('/OtpVerifiy',{mobNo:phoneNumber}) }} 

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

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

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

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