l2s*_*ver 14 reactjs react-router
是否有一种简单的方法来返回当前的路由器地址.
IE浏览器,如果我在页面上,我只想根据反应路由器查看我所在的页面.
因此,localhost/admin/users将返回admin/users
显然,我可以通过解析位置获得相同的结果,但我想知道反应路由器是否提供了一个简单的机制来执行此操作,就像它提供params道具一样?
Ale*_*van 35
如果您使用的是1.0或更新版本,则可以location在React组件中获得与路径匹配的prop.所以你只需输入
this.props.location.pathname
Run Code Online (Sandbox Code Playgroud)
得到你想要的.
小智 15
this.props.location.pathname 仅给出路由路径.
window.location.href为您提供完整的URL,如/sf/answers/2787662461/所示
k32*_*32y 10
对于使用浏览器窗口对象的非反应、纯基于 JavaScript 的解决方案。假设当前页面的 URL 是这样的https://hostname:port/path?query。
window.location.href // returns the full URL 'https://hostname:port/path?query'
Run Code Online (Sandbox Code Playgroud)
window.location.pathname // returns just the 'path' part of the full URL.
Run Code Online (Sandbox Code Playgroud)
window.location.search // returns just the '?query' part of the full URL.
Run Code Online (Sandbox Code Playgroud)
window.location.port // returns the 'port'.
Run Code Online (Sandbox Code Playgroud)
window.location.hostname // returns just the 'hostname' part of the URL.
Run Code Online (Sandbox Code Playgroud)
window.location.host // returns the hostname and port (hostname:port) part of the URL.
Run Code Online (Sandbox Code Playgroud)
window.location.protocol // returns the protocol (https)
Run Code Online (Sandbox Code Playgroud)
window.location.origin // returns the base URL (https://hostname:port)
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/Location 。
你也可以试试
location.pathname
Run Code Online (Sandbox Code Playgroud)
它可能会工作,而其他方法不像我做的那样
小智 8
对于 React 功能组件
import { useLocation } from 'react-router-dom';
const MyComponent = () => {
let location = useLocation();
...useState
useEffect(() => {
console.log(location.pathname);
}, []);
return ();
};
export default MyComponent;
Run Code Online (Sandbox Code Playgroud)
还有许多其他选项:https : //dev.to/finallynero/hooks-introduced-in-react-router-v5-1-7g8
对于反应路由器 DOM v6
const { pathname } = useLocation();
Run Code Online (Sandbox Code Playgroud)
如果有人需要则导入
import { useLocation } from "react-router-dom";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48666 次 |
| 最近记录: |