【发布时间】:2023-03-22 23:04:01
【问题描述】:
我有几条路线,根据我的App.js 中的以下路径呈现不同的组件
<Route
path="/spaces"
render={({ match: { url } }) => (
<>
<Route path={[`${url}`, `${url}/members`, `${url}/about`, `${url}/admin`]} component={Spaces} exact />
</>
)}
/>
<Route
path="/profile"
render={({ match: { url } }) => (
<>
<Route path={[`${url}`, `${url}/comments`, `${url}/spaces`, `${url}/cloud`]} component={Spaces} exact />
</>
)}
/>
在我的 Space.js 组件中,我根据 url 创建了一个条件渲染,因此当用户在例如 /spaces/members 或 /spaces/members/ 时,将渲染一个组件等..
function Spaces({ match }) {
let path = `${match.url}`;
let Content;
let admin;
let profile;
if (path == '/spaces/members/' || path == '/spaces/members') {
Content = <SpaceMembers />;
} else if (path == '/spaces/' || path == '/spaces') {
Content = <SpaceContent />;
} else if (path == '/spaces/about' || path == '/spaces/about/') {
Content = <SpaceAbout />;
} else if (path == '/spaces/admin' || path == '/spaces/admin/') {
admin = true;
Content = <SpaceAdmin />;
} else if (path == '/profile' || path == '/profile/') {
profile = true;
typeContent = <ProfileContent />
} else if (path == '/profile/comments' || path == '/profile/comments') {
profile = true;
Content = <ProfileSpace />
}
return (
<div>
<div className='page-content' style={{ maxWidth: !admin ? '980px': '800px'}}>
<div className='profile-page tx-13'>
{(!profile || admin) ? <Cover admin={admin} profile={profile}/> : <CoverProfile admin={admin} profile={profile}/> }
{Content}
</div>
</div>
</div>
);
}
export default Spaces;
目前条件渲染运行良好。但作为 React 的新手,我的问题是,这是正确的做法还是有其他更好的方法?
现在恐怕我需要稍后将自定义 /:id 添加到路径中,并且条件可能不起作用。
【问题讨论】:
-
我会将 if else 替换为 react-router 开关。如果我正确理解了您的问题,它专门针对您要解决的问题。 reactrouter.com/web/api/Switch
-
@isherwood 非常感谢您,先生,我会调查的。
-
不是我。不过,不客气。
-
@AlyaKra 您有一个错误,因为您在 App.js(您创建路由的组件)中使用了
useLocation...您需要在根据路径名更改的组件中使用它。 (match.url和location=> stackoverflow.com/questions/47762475/…) -
@AlyaKra 是的,您可以创建一个带有 switch case 条件的组件,该条件例如根据位置返回多个组件并将其导入其他组件中
标签: javascript reactjs