reactjs - 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/
解决方案
推荐阅读
- c# - listview 上的项目在拉动时重复以刷新 xamarinforms
- sql - 通过 Postgres 中的值组获取滚动的更改总数
- java - 根据值动态设置setter
- python - 哪个 Python 错误消息用于失败的图遍历以及如何处理 mypy 声称该函数没有返回语句?
- linux - 由于 Ubuntu 中缺少 .env 文件,Android 应用程序无法在模拟器中安装
- reactjs - 到达路由器 - 使用 URL 加载组件
- node.js - Celebrate/Joi 在错误的情况下返回 HTML 而不是 JSON
- date - 使用两个输入字段创建具有计算机属性(getter 和 setter)的 Date 对象 Ember JS
- c# - 如果计数器未达到索引的最后一个,则防止 for 循环打印出重复的内容
- data-structures - 另一个数组中起始位置的名称