javascript - 渲染 Prop 与 HOC?

标签 javascript reactjs react-hooks higher-order-components

我正在尝试从头开始学习 React 并深入了解概念!

今天我在搜索 HOC,Render Props 以及两者之间的区别。我已经检查了两者的渲染时间。我在 render 中写了一个 console.log('rendered') 来检查浏览器控制台中的渲染时间。

HOC:当我使用 HOC 编写一个可用的组件时,我看到在我为 HOC 渲染的 props 和使用 HOC 的组件的每次更改之后。

渲染 Prop :在这种情况下,我已经更改了 Prop ,但只渲染了包装器组件。因为使用 render props 我们只加载一个组件并注入(inject)代码以使用该组件功能!

那么,使用 Render Props 代替 HOC 组件有好处吗?还是 HOC 组件可用且功能强大?

谢谢

最佳答案

HOCRender Props 和现在的 hooks 都服务于相同的目的:在组件之间共享有状态逻辑 .实际上没有办法判断哪个更好或更差。一切都取决于您的用例。


高阶组件 是可组合的。嵌套它们很容易

const withProps = (Component) => connect(mapState, mapDispatch)(<Component foo='bar' />)

子函数作为一个函数对于可组合性来说是一个糟糕的模式,嵌套看起来很像一个 callback hell ,因为它们需要在 jsx block 中执行

const Component = () => {
  return (
    <Consumer>
      {
        props => (
          <ThemeConsumer>
            {
              theme => <Child {...props} {...theme} />
            }
          </ThemeConsumer>              
        )                  
      }
    </Consumer>
  )
}

另一方面,render props 很容易设置,样板文件更少,在大多数情况下更容易推理。


Hooks 带来了两全其美的优势

hooks 是可组合的,可以轻松嵌套,并且很容易推理原因毕竟它们只是普通的旧函数

const useConfig = () =>{
  const customProps = useCustomProps()
  const theme = useContext(ThemeContext)

  return [customProps, theme]
}

const Component = () => {
  const [props, theme] = useConfig()
}

但再次强调:没有最佳模式这样的东西。这只是您要在哪里使用它的问题。

关于javascript - 渲染 Prop 与 HOC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58855777/

相关文章:

reactjs - React Redux 连接组件与异步 Action 测试

javascript - 未捕获的类型错误 : Cannot read property 'length' of undefined in example d3 code

javascript - Webpack css 加载器问题 "!!../../node_modules/css-loader/index.js!./main.css"

javascript - 使用 jQuery 更改 div 类

reactjs - 如何将复选框值添加到reactJS中的setState数组

javascript - React 代码无法在渲染之前设置全局上下文

javascript - 欢迎消息 - 类型错误 : Cannot read property 'user' of undefined

javascript - React-testing-library 为什么 toBeInTheDocument() 不是一个函数

javascript - 如何使用钩子(Hook)切换 React 组件与 Redux?

javascript - React hooks 对象更新在 Safari 浏览器上出现奇怪的行为