首页 > 解决方案 > React 使用历史在新选项卡中打开

问题描述

我正在尝试在新选项卡中打开链接。

我在 Navigation.js 文件中有我的路由器。

import {
  HashRouter as Router,
  Switch,
  Route
} from "react-router-dom";

...

const PrivateRoute = ({ component, ...options }) => {
  const login = useSelector((state) => state.login);
  const finalComponent = login.logged ? component : Login;

  return <Route {...options} component={finalComponent} />;
};

...

<PrivateRoute exact path="/test/myTest" component={Test} />

...

然后,我在组件中有一个方法,我在其中进行一些验证并在打开链接之前设置 localStorage 值。

import { useHistory } from "react-router-dom";

....

const history = useHistory();

....

const myMethod = async () => {
  // There are some validations here where I might return a warning message and not open the link
  // If it passes all the validations:
  await localStorage.setItem("id", id);
  await localStorage.setItem("name", name);
  history.push('/test/myTest');   // This works perfectly, but navigates in the same tab. I want to open in a new tab.
}

我试图将其更改history.push('/test/myTest')window.open('/test/myTest', '_blank'). 但是,它不起作用,因为链接变为:http://localhost:3000/test/myTest#/而不是http://localhost:3000/#/test/myTest/

标签: reactjsreact-router-dom

解决方案


推荐阅读