【问题标题】:How to pass variable id with history.push()如何使用 history.push() 传递变量 id
【发布时间】:2020-07-07 05:30:22
【问题描述】:

我正在使用 react-router 库进行导航,并使用 history.push() 来导航 onClick。当用户点击一行时,他们将被导航到“otherPage”。在“otherPage”中,我想使用变量“id”。如何传递这个变量?

function handleRowClick(id: number): void {
    // navigates user to another page
    history.push('/otherPage');
}

【问题讨论】:

  • 请不要在标题中加上“标签”,这是标签的用途。

标签: reactjs typescript react-router react-hooks tsx


【解决方案1】:
history.push(route, state);

可选的state 参数是一个带有您的自定义路由参数的对象。

state 对象在您的组件内部可用(如果没有,您可以使用 withRouter hoc 包装它)

this.props.location.state 

类组件

高阶组件

import { withRouter } from 'react-router';
/* other dependencies */

class YourClassComponent {
  render() {
    const { location } = this.props;
    console.log(location.state);

    return (
      /* some jsx here */ 
    );
  }
}

export default withRouter(YourClassComponent);

功能组件

高阶组件

import { withRouter } from 'react-router';
/* other dependencies */

const YourFunctionalComponent = ({ location }) => {
  console.log(location.state);

  return (
    /* some jsx here */ 
  );
};

export withRouter(YourFunctionalComponent);

反应钩子

import { useLocation } from 'react-router-dom';
/* other dependencies */

const YourFunctionalComponent = ({ location } ) => {
  const location = useLocation();
  console.log(location.state);

  return (
    /* some jsx here */ 
  );
};

【讨论】:

  • 好的,谢谢,但是在使用 React Hooks 时如何使用 'otherPage' 中的变量?
  • @Io7 我添加了有关withRouter hoc 的信息,希望对您有所帮助:)
猜你喜欢
  • 1970-01-01
  • 2021-03-08
  • 2021-06-06
  • 2020-12-20
  • 2011-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多