我正在使用react-router库进行导航,并使用history.push()来导航onClick。当用户单击一行时,他们将被导航到“ otherPage”。在“ otherPage”中,我想使用变量“ id”。如何传递此变量?
function handleRowClick(id: number): void {
// navigates user to another page
history.push('/otherPage');
}
答案 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 */
);
};