【发布时间】:2022-10-15 13:23:57
【问题描述】:
我的项目一直使用react-router-dom...这是我的代码:
App.js:
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
function App() {
const currentUser = true;
return (
<Router>
<Topbar />
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/register">
{currentUser ? <Home /> : <Register />}
</Route>
<Route path="/login">{currentUser ? <Home /> : <Login />}</Route>
<Route path="/post/:id">
<Single />
</Route>
<Route path="/write">{currentUser ? <Write /> : <Login />}</Route>
<Route path="/settings">
{currentUser ? <Settings /> : <Login />}
</Route>
</Switch>
</Router>
);
}
顶栏.jsx:
function Topbar() {
const user = true;
return (
<div className="top">
<div className="topLeft">
<span className="topIcon iconfont icon-weixin"></span>
<span className="topIcon iconfont icon-weibo"></span>
<span className="topIcon iconfont icon-douyin"></span>
</div>
<div className="topCenter">
<ul className="topList">
<li className="topListItem"><Link className="link" to="/">HOME</Link></li>
<li className="topListItem"><Link className="link" to="/">ABOUT</Link></li>
<li className="topListItem"><Link className="link" to="/">CONTACT</Link></li>
<li className="topListItem"><Link className="link" to="/write">WRITE</Link></li>
<li className="topListItem">
{ user && "LOGOUT" }
</li>
</ul>
</div>
<div className="topRight">
{
user ? (
<img className="topImg" src="https://assets.imgix.net/hp/snowshoe.jpg?auto=compress&w=900&h=600&fit=crop" alt="profile" />
) : (
<ul className="topList">
<li className="topListItem"><Link className="link" to="/login">LOGIN</Link></li>
<li className="topListItem"><Link className="link" to="/register">REGISTER</Link></li>
</ul>
)
}
<span className="topSearchIcon iconfont icon-sousuo"></span>
</div>
</div>
)
}
当我单击<Link /> 到<Write/> 组件时,URL 改变了,但页面没有改变......有谁知道为什么?很多人说exact 属性,但我已经在<Home/> 组件中添加了它。
【问题讨论】:
-
在 app.js 中,您似乎缺少对组件的导入。通常你描述的可能是应用程序错误,看看控制台,你得到了什么?
-
谢谢,我找到了解决方案...这是版本问题,我使用react18和react-router-dom v5 ...我将react-router-dom更改为v6,问题解决了!
标签: javascript reactjs react-router react-router-dom