如何使用 history.push 传递多个参数?
How do I pass multiple parameters using history.push?
在 React 中,我尝试使用 history.push 传递路径名和另一个参数。
当它执行应用程序重定向到指定的页面,但状态未定义,所以我无法获取其他参数。
<Route path='/main' exact component={Main} />
import { useHistory } from "react-router-dom";
var history = useHistory();
function handleSubmit(event) {
event.preventDefault();
history.push("/main", { state: 'test'});
};
const Main= (props) => {
console.log(props.location.state);
};
export default Main;
在 Main 中,props.location.state 未定义。你能帮帮我吗?
您可能想尝试推送的对象版本:
function handleSubmit(event) {
event.preventDefault();
history.push({
pathname: "/main",
state: 'test',
});
};
同时请确保接收组件也在接收 route props。
const Main= (props) => {
console.log(props.location.state);
};
如果不是,则确保通过 useLocation
挂钩或 withRouter
高阶组件访问 location
对象,将它们作为 props 注入。
要在没有路由道具或 withRoute
HOC 的情况下获取功能组件中的位置状态,您可以使用 useLocation
代替:
import { useHistory } from "react-router-dom";
const Main= () => {
const location = useLocation();
console.log(location);
};
并通过位置状态传递多个变量,使用对象:
history.push("/page1", { pathname: "test", anotherParam: "test2" });
注意:history.push
的第二个参数已经是state了,不用再命名为state
实例:
在 React 中,我尝试使用 history.push 传递路径名和另一个参数。 当它执行应用程序重定向到指定的页面,但状态未定义,所以我无法获取其他参数。
<Route path='/main' exact component={Main} />
import { useHistory } from "react-router-dom";
var history = useHistory();
function handleSubmit(event) {
event.preventDefault();
history.push("/main", { state: 'test'});
};
const Main= (props) => {
console.log(props.location.state);
};
export default Main;
在 Main 中,props.location.state 未定义。你能帮帮我吗?
您可能想尝试推送的对象版本:
function handleSubmit(event) {
event.preventDefault();
history.push({
pathname: "/main",
state: 'test',
});
};
同时请确保接收组件也在接收 route props。
const Main= (props) => {
console.log(props.location.state);
};
如果不是,则确保通过 useLocation
挂钩或 withRouter
高阶组件访问 location
对象,将它们作为 props 注入。
要在没有路由道具或 withRoute
HOC 的情况下获取功能组件中的位置状态,您可以使用 useLocation
代替:
import { useHistory } from "react-router-dom";
const Main= () => {
const location = useLocation();
console.log(location);
};
并通过位置状态传递多个变量,使用对象:
history.push("/page1", { pathname: "test", anotherParam: "test2" });
注意:history.push
的第二个参数已经是state了,不用再命名为state
实例: