ChatGPT解决这个技术问题 Extra ChatGPT

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

我们如何在 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');
          });
Route 呈现的组件应该可以访问 this.props.locationthis.props.history 等。我认为您不再需要在 v4 中使用 ref。尝试做this.props.history.push('/template');
不是 ref ,指向这个的是变量; this.props.history.push('/template');带我到下一页,但我想和他们一起传递道具 .ref = this;
您正在尝试将 props 传递给与路由匹配的组件?我认为 this GitHub thread 解决了您的问题。
您能否将其中一个回复标记为“答案”。我相信花时间打字的人会很感激。

S
Shubham Khatri

首先,您不需要执行 var r = this;,因为 if statement 中的 this 指的是回调本身的上下文,因为您使用的是箭头函数,所以它指的是 React 组件上下文。

根据文档:

历史对象通常具有以下属性和方法: length -(数字)历史堆栈中的条目数 action -(字符串)当前操作(PUSH、REPLACE 或 POP)位置 -(对象)当前位置。可能具有以下属性: pathname - (string) URL 搜索的路径 - (string) URL 查询字符串 hash - (string) URL hash 片段状态 - (string) 提供给例如 push( path, state) 当这个位置被压入堆栈时。仅在浏览器和内存历史记录中可用。 push(path, [state]) - (function) 将新条目推送到历史堆栈 replace(path, [state]) - (function) 替换历史堆栈上的当前条目 go(n) - (function) 移动历史堆栈中 n 个条目的指针 goBack() - (function) 等价于 go(-1) goForward() - (function) 等价于 go(1) block(prompt) - (function) 防止导航

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

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 路由呈现的组件中,您可以访问传递的道具,如

this.props.location.state.detail

另请注意,在使用道具中的历史或位置对象时,您需要将组件与 withRouter 连接。

根据文档:

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


是的,那行得通。谢谢!但不确定为什么 this.props.history.push('/template',response.data) 不起作用。根据 push(path, [state]) 的文档,您认为它不应该起作用吗?
谢谢你!就我而言,我只是直接传递历史,所以我通过 this.props.history.location.state.propName 访问了我的道具 -
@SanketPatel 你需要这样做 this.props.history.push('/template', {response: response.data})
导航时是否可以在新选项卡中打开路线,同时在状态变量中传递数据,您可以将道具传递给历史对象?
goBack() 呢?当使用 goBack() 导航返回时,我在 props.location 或 props.history.location 中看不到任何历史状态。使用 push() 向前导航它工作正常
B
Branislav Lazic

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

};


非常感谢,除了您的回答,找不到更新的替代方案!
完美的!!刚刚好!!。正是我一直在寻找的。
A
AmerllicA

对于早期版本:history.push('/[pathToSomeWhere]', yourData);并获取相关组件中的数据,如下所示: this.props.location.state // 它等于 yourData 对于较新的版本,上述方式效果很好,但有一种新方式:history.push({ pathname: ' /[pathToSomeWhere]',状态:你的数据,});并获取相关组件中的数据,如下所示: Class Component this.props.location.state; // 它等于 yourData 函数组件 const location = useLocation();位置.状态; // 它等于 yourData

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

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

提示state 键名应在最新版本中使用。


D
Diamond

如果您需要传递 URL 参数

Tyler McGinnis 在他的网站上有一个很棒的帖子解释,Link to the post

以下是代码示例:

在 history.push 组件上:this.props.history.push(`/home:${this.state.userID}`) 在路由器组件上定义路由: 在 Home 组件上:

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

我有类似的东西,但是如果我刷新页面它会完全崩溃
@rabiaasif 因为数据不再存在,您需要将其持久化或将其存储在本地存储中
D
Devgig

使用 Hooks 响应 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>
  );
}

你最好做 useLocation<IState>() 这样你就不必在下一行断言
A
Abdulhakim Zeinu

经过

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

import React from 'react';

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

}

Here 是一个工作示例


有没有办法将 URL 参数作为键值对发送? ?key1=value1&key2=value2
S
Sangeet Agarwal

我创建了一个自定义 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}`,
});
                  

Z
Zera FounderX

您可以使用 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
}

奖金

如果要重置接收状态。使用 history 替换位置,如下所示

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

currentPath目标组件 路径 resetState 是新的值状态,无论你想要什么


非常简洁的答案。使用 React Router v5,您可以简单地使用 location() hook const location = useLocation() const data = location.state
s
soma iyappan

要使用 React 16.8 (withHooks) 功能组件,您可以使用这种方式 我们将 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 router dom version 6.2.1 useHistory() deprecated changed useNavigate()

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

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

j
joedotnot

没有必要使用 withRouter。这对我有用:

在您的父页面中,

<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 方法。


我认为您不需要 withRouter,因为您使用 BrowserRouter 包装了组件,它的工作原理相同。
是的,您将 props 向下传递到包含 history 道具的每个组件中。
P
P Mill

要使用 React 16.8+(withHooks),你可以使用这种方式

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


k
kamal pandey

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

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

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


这与 React Router 4 完全无关。