【问题标题】:How to pass params with history.push/Link/Redirect in react-router v4?如何在 react-router v4 中通过 history.push/Link/Redirect 传递参数?
【发布时间】:2018-02-20 11:04:56
【问题描述】:

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

标签: reactjs react-router


【解决方案1】:

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

根据文档:

历史对象通常具有以下属性和方法:

  • length - (number) 历史堆栈中的条目数
  • action -(字符串)当前操作(PUSH、REPLACE 或 POP)
  • location - (object) 当前位置。可能具有以下属性:

    • pathname - (string) URL 的路径
    • search - (string) URL 查询字符串
    • hash - (string) URL 哈希片段
    • state - (字符串)提供给例如位置特定的状态。 push(path, state) 当这个位置被推到 堆。仅在浏览器和内存历史记录中可用。
  • push(path, [state]) - (function) 将新条目推送到历史堆栈中
  • replace(path, [state]) - (function) 替换历史堆栈上的当前条目
  • go(n) - (function) 将历史堆栈中的指针移动 n 个条目
  • goBack() - (function) 等价于 go(-1)
  • goForward() - (函数) 等价于 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路由渲染的组件中,你可以访问像传递的props

this.props.location.state.detail

另外请记住,当使用 props 中的历史或位置对象时,您需要将组件与 withRouter 连接。

根据文档:

withRouter

您可以访问历史对象的属性和最近的 &lt;Route&gt;'s 通过 withRouter 高阶组件匹配。 withRouter 每次路由更改时都会重新渲染其组件 与&lt;Route&gt; 相同的道具渲染props: { 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() 向前导航效果很好
【解决方案2】:

扩展解决方案(由 Shubham Khatri 建议)以用于 React hooks(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]);

};

【讨论】:

  • 非常感谢,除了您的回答,找不到更新的替代方案!
  • 完美!!刚刚好!!。正是我一直在寻找的。​​span>
【解决方案3】:
  1. 对于早期版本:

    history.push('/[pathToSomeWhere]', yourData);
    

    并获取相关组件中的数据,如下所示:

    this.props.location.state // it is equal to yourData
    
  2. 对于较新的版本上述方法效果很好,但有一种新方法:

    history.push({
      pathname: '/[pathToSomeWhere]',
      state: yourData,
    });
    

    并获取相关组件中的数据,如下所示:

    • 类组件

      this.props.location.state; // it is equal to yourData
      
    • 功能组件

      const location = useLocation();
      location.state; // it is equal to yourData
      

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

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

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

【讨论】:

    【解决方案4】:

    你可以使用,

    this.props.history.push("/template", { ...response }) 要么 this.props.history.push("/template", { response: response })

    那么你就可以通过下面的代码从/template组件中访问解析出来的数据了,

    const state = this.props.location.state

    阅读更多关于 React Session History Management

    【讨论】:

    • 这个逻辑对我有用,而 history.push 和 back_url 处于状态 this.props.history.push(redirect_url,{ back_url: '/needing_url' });并通过 this.props.location.state.back_url 在登录页面获取此信息
    【解决方案5】:

    如果需要传递 URL 参数

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

    这里是代码示例:

    1. 关于 history.push 组件:

      this.props.history.push(`/home:${this.state.userID}`)

    2. 在路由器组件上定义路由:

      &lt;Route path='/home:myKey' component={Home} /&gt;

    3. 在 Home 组件上:

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

    【讨论】:

    • 我有这样的东西,但是如果我刷新页面它会完全崩溃
    • @rabiaasif 因为数据已经不存在了,您需要将其持久化或将其存储在本地存储中
    【解决方案6】:

    使用 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&lt;IState&gt;() 这样你就不必在下一行断言
    【解决方案7】:

    通过

    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
    【解决方案8】:

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

    【讨论】:

      【解决方案9】:

      您可以使用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
      【解决方案10】:

      不需要使用 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 属性的每个组件中。
      【解决方案11】:

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

      【讨论】:

        【解决方案12】:

        要使用 React 16.8 (withHooks) 功能组件,您可以这样使用
        我们将电话号码发送到下一页
        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>
            )
        

        【讨论】:

          【解决方案13】:

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

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

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

          【讨论】:

          • 这与 React Router 4 完全无关。
          猜你喜欢
          • 2018-01-17
          • 1970-01-01
          • 1970-01-01
          • 2018-01-29
          • 2018-02-28
          • 1970-01-01
          相关资源
          最近更新 更多