如何使用 history.push() 传递变量 id

How to pass variable id with history.push()

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

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

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

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

this.props.location.state 

Class 组件

高阶组件

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);

React 钩子

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

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

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