如何使用history.push传递多个参数?

问题描述 投票:0回答:3

在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 未定义。你能帮我吗?

reactjs parameters react-router-dom
3个回答
1
投票

您可能想尝试推送的对象版本:

function handleSubmit(event) {
  event.preventDefault();
  history.push({
    pathname: "/main",
    state: 'test',
  });
};

另请确保接收组件也正在接收route props

const Main= (props) => {
  console.log(props.location.state);
};

如果没有,请确保通过

location
钩子或
useLocation
高阶组件访问
withRouter
对象,将它们作为 props 注入。


0
投票

要在没有路线道具或

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

实例:

Edit React Router - 404 - Navbar condition (forked)


0
投票

我们也可以利用这种格式

 history.push({
  pathname: '/some-path',
  search: '?q=india&id=12345'
 })
© www.soinside.com 2019 - 2024. All rights reserved.