我有一个App.jsx,它路由到(呈现)不同的组件。
但是,我在<NavigationBar />和h1标记Router和Switch之间设置了一个,因为我需要为每个页面呈现这两个组件。
所以现在我想要的是获取浏览器地址栏上显示的当前路由名称/路径名。当我单击不同的链接(Link)来呈现不同的组件时,这个路径正在改变。
但是path值是相同的/,尽管每次单击Link都会改变路径。我甚至使用了componentDidUpdate,但是它没有工作,因为它导致了错误
最大更新深度超过组件
这是我的App.jsx
import React, { Component } from "react";
import "./App.css";
import "./css/custom.css";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import NavigationBar from "./pages/homepage-components/1-navbar";
import HomePage from "./pages/HomePage";
import Post from "./pages/Post";
class App extends Component {
constructor(props) {
super(props);
this.state = {
currentPath: "",
};
}
componentDidMount() {
this.setState({
currentPath: window.location.pathname,
});
}
render() {
return (
<Router>
{/* --------------- Navigation Bar --------------- */}
<NavigationBar />
<h1>Path is: {this.state.currentPath}</h1>
{/* --------------- End of Navigation Bar --------------- */}
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/post" component={Post} />
</Switch>
</Router>
);
}
}
export default App;即使不同的组件呈现为路径更改,this.state.currentPath的值也不会更新。
有人能帮忙吗?
发布于 2020-07-30 21:26:25
useLocation钩子提供当前位置:
function NavigationHeader() {
const location = useLocation();
return <h1>Path is: {location.pathname}</h1>;
}https://stackoverflow.com/questions/63181535
复制相似问题