【问题标题】:Conditional rendering on React routesReact 路由上的条件渲染
【发布时间】: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.urllocation => stackoverflow.com/questions/47762475/…
  • @AlyaKra 是的,您可以创建一个带有 switch case 条件的组件,该条件例如根据位置返回多个组件并将其导入其他组件中

标签: javascript reactjs


【解决方案1】:

我建议您创建一个配置文件,在其中声明所有可用的路由,然后创建一个路由文件并从 path.js 导入所有路径,并创建一个包含所有道具的对象列表- 精确,组件,路径。在 path,s value 中,调用您从 paths.js 导入的路径。它会做的是,它为您创建了一个很好的结构来处理一般的路由

【讨论】:

  • 有趣!所以你建议创建一种全局变量?我打算用 Redux 来声明所有路由等。
  • 是的,有一些变量经常在多个组件中使用 inreact,例如 - 路由。虽然我们可以在每次使用router的时候静态地写路径,但是inling run,当我们的应用程序变得足够大并且我们需要改变一些特定的变量时,改变值变得非常困难,这就是为什么我总是使用全局对象包含可重复的变量键值对,键是名称,值是存储的日期,在您的示例中它将是路由路径。
猜你喜欢
  • 1970-01-01
  • 2019-04-25
  • 1970-01-01
  • 2021-10-27
  • 2020-01-12
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
相关资源
最近更新 更多