使用 react.js 执行基于当前 URL 的条件并反应路由器 v6
Performing a condition based on the current URL with react.js and react router v6
使用React.js & React 路由器 v6
有什么方法可以从当前 URL 中提取信息?假设我当前的 URL 是这样的:localhost:3000/about/x567gfh67ssd90g
我只是想根据当前 URL 执行一个条件。有什么可行的方法吗?
import { useLocation } from "react-router-dom";
const Component = () => {
const location = useLocation();
useEffect(() => {
console.log(location);
});
return ();
};
您可以使用 useLocation 获取路径名。
您还可以将 connected-react-router 添加到您的项目中。这样您就可以访问 redux-store 中的所有当前路线信息。这也将允许您通过 SPA 进行“时间旅行”。当您点击后退按钮而不是转到上一页时,您可以通过状态返回。
import React from 'react';
import { render } from 'react-dom';
import { Provider, ReactReduxContext } from 'react-redux';
import { ConnectedRouter } from "connected-react-router";
import { store, history } from './Store/store';
import { App } from './App/App';
render(
<Provider store={ store } context={ ReactReduxContext } >
<ConnectedRouter context={ ReactReduxContext } history={ history }>
<App />
</ConnectedRouter>
</Provider>,
document.getElementById('app')
);
如果您在浏览器中安装 redux-devTools,您可以像这样查看所有 URL 数据 - 显然这有点高级,但您可以访问所需的一切.
使用React.js & React 路由器 v6
有什么方法可以从当前 URL 中提取信息?假设我当前的 URL 是这样的:localhost:3000/about/x567gfh67ssd90g
我只是想根据当前 URL 执行一个条件。有什么可行的方法吗?
import { useLocation } from "react-router-dom";
const Component = () => {
const location = useLocation();
useEffect(() => {
console.log(location);
});
return ();
};
您可以使用 useLocation 获取路径名。
您还可以将 connected-react-router 添加到您的项目中。这样您就可以访问 redux-store 中的所有当前路线信息。这也将允许您通过 SPA 进行“时间旅行”。当您点击后退按钮而不是转到上一页时,您可以通过状态返回。
import React from 'react';
import { render } from 'react-dom';
import { Provider, ReactReduxContext } from 'react-redux';
import { ConnectedRouter } from "connected-react-router";
import { store, history } from './Store/store';
import { App } from './App/App';
render(
<Provider store={ store } context={ ReactReduxContext } >
<ConnectedRouter context={ ReactReduxContext } history={ history }>
<App />
</ConnectedRouter>
</Provider>,
document.getElementById('app')
);
如果您在浏览器中安装 redux-devTools,您可以像这样查看所有 URL 数据 - 显然这有点高级,但您可以访问所需的一切.