【问题标题】:Common conditional rendering pattern in reactreact中常见的条件渲染模式
【发布时间】:2020-11-17 14:47:45
【问题描述】:

我是新来的反应和钩子。我有四个页面(使用反应钩子的功能组件),我需要根据某些条件在其中呈现另一个组件。 我知道我总是可以进行条件渲染。 喜欢,

第1页
返回是有效的?组件1:组件2;

第2页
返回是有效的?组件1:组件3;

第3页
返回是有效的?组件1:组件4;

所以这里的component1(如果条件为真,我想在每个页面中呈现)对于所有四个页面都是相同的。 但似乎我需要对所有四个页面/功能组件执行此操作。我不想为多个组件重复此代码,因为它使组件不可读并加载许多代码行。

我想知道如果条件为真而不在所有四个页面中编写重复代码,是否有任何其他方法可以渲染说 component1? 说使用高阶组件(HOC)或自定义钩子或任何拦截器模式?

例如,使用 HOC,

withValidation(component2)
withValidation(component3)
withValidation(component4)

这里,如果条件为真,withValidation HOC 返回组件1(它将是另一个组件)或返回包装的组件。可行吗?

【问题讨论】:

    标签: reactjs react-native react-hooks


    【解决方案1】:

    你如何处理路由?因为它可以像这样使用 react-router-dom 来完成(组件名称只是示例):

    import React from 'react'
    import { Switch, Route } from 'react-router-dom'
    import Header from './header'
    import User from './user'
    import Repository from './repository'
    
    const Home = () => {
      return (
        <>
          // <Header> is the common component, you can use conditions instead like {visible && <Header />}
          <Header /> 
          // here below we manage how components depends on url
          <Switch>
            <Route exact path="/:user" component={() => <User />} />
            <Route exact path="/:user/:repository" component={() => <Repository />} />
          </Switch>
        </>
      )
    }
    

    结合条件和路由,您可以创建相当复杂的逻辑,说明应该渲染什么以及何时渲染。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-16
      • 2021-05-22
      • 1970-01-01
      • 2017-11-22
      • 2020-12-28
      • 2016-08-03
      • 2018-09-10
      • 2021-06-07
      相关资源
      最近更新 更多