在 React 中,特别是当你使用像 react-router-dom 这样的路由库时,history.push 是一个非常常用的方法来导航到不同的页面或路由。如果你想要携带参数,通常有以下几种方法可以做到这一点:
- 查询参数(Query Parameters) :
你可以通过查询参数来传递数据。这些参数会附加在 URL 的 ? 后面,并以 key=value 的形式出现。
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
const handleClick = () => {
history.push('/target-route?param1=value1¶m2=value2');
};
// ...
}
在目标组件中,你可以使用 useLocation 钩子来获取这些查询参数:
import { useLocation } from 'react-router-dom';
function TargetComponent() {
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
const param1 = queryParams.get('param1');
const param2 = queryParams.get('param2');
// ...
}
- 状态(State) :
history.push 也可以接受一个对象作为参数,该对象可以包含一个 state 属性。这个 state 会在导航过程中被传递,但不会作为 URL 的一部分显示。
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
const handleClick = () => {
history.push({
pathname: '/target-route',
state: { param1: 'value1', param2: 'value2' }
});
};
// ...
}
在目标组件中,你可以通过 location.state 来获取这些参数:
import { useLocation } from 'react-router-dom';
function TargetComponent() {
const location = useLocation();
const { param1, param2 } = location.state || {};
// ...
}
注意,使用 state 传递的参数不会在 URL 中显示,因此它们对于不想让用户看到或编辑的数据特别有用。但是,因为它们是通过浏览器的历史记录传递的,所以如果用户刷新页面或通过其他方式直接访问该路由,这些状态数据可能会丢失。
- 路径参数(Path Parameters) :
虽然 history.push 本身不直接支持路径参数,但你可以通过构建包含参数的 URL 字符串来模拟这一行为。然后,你可以在目标组件中解析这些参数。但是,这通常需要在你的路由配置中设置一些额外的逻辑来匹配和解析这些参数。这在使用像 react-router-dom 的 <Route> 组件时更为常见。
路由定义:
<Route path="/home/:val"
component={Component}
exact
/>
获取参数:
const val = this.props.match.params.val;