如何通过history.push()传递变量ID

时间:2020-03-26 14:36:44

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

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

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

1 个答案:

答案 0 :(得分:2)

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 */ 
  );
};