检查 Reactjs 中的路径链接



我想检查 React Js 中的路径。

例如 =>/dashboard/dashboard/xyz

其中xyz可以是任何其他路径。

我该怎么做?

我想做/dashboard/*但这不起作用。

const renderdashboard = (pathname === "/dashboard/*") ? ( <Dashboard /> ) : null;

您可能应该使用 react-router。

话虽如此,React 是一个显示框架,不包含任何代码。使用常规的Javascript来检查它。

使用window.location获取位置,如此处所述, 然后使用任何字符串函数进行比较。

例子:

window.location.pathname.includes('/dashboard/');
window.location.pathname.search(/^/dashboard/) > -1;

使用 react-router 和其他路由库在 react 中进行路由。

在这些库的帮助下,可以轻松创建可选参数。

下面是使用react-router的问题的示例代码

import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
function BasicExample() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/dashboard/xyz">Dashboard</Link>
</li>
</ul>
<hr />
<Route exact path="/" component={Home} />
<Route path="/dashboard/:something?" component={Dashboard} />
</div>
</Router>
);
}
function Home() {
return (
<div>
<h2>Home</h2>
</div>
);
}
function Dashboard({ match }) {
return (
<div>
<h2>Dashboard {match.params.something}</h2>
</div>
);
}

export default BasicExample;

希望有帮助!!

您可以测试一个字符串是否包含另一个带有正则表达式的字符串:

//dashboard//.test(pathname) ? renderstuff.. : null

请注意,React 本身与路径没有任何关系,这更多的是关于原版 javascript 和/或路由库,所以将来检查你的标签

path="/dashboard/:xyz?">

你可以使用 react-router-dom npm,并使用 Route。

<Route path="/dashboard/:xyz?" component={Dashboard} />

在组件中,您可以检查参数并定义状态以根据状态渲染某些内容。

componentDidMount() {
const isXYZ = this.props.match.params.xyz;
if (xyz) {
// path = /dashboard/something
} else {
// path = /dashboard
}
}

最新更新