【问题标题】:WithProps vs withHandlersWithProps 与 withHandlers
【发布时间】:2017-07-24 06:38:14
【问题描述】:

我一直在查看 react recompose 库并试图在这里掌握差异,结果是一样的,尝试阅读文档,但更加困惑,为什么有两种方法可以做同样的事情?

const enhance = compose(
  withState('counter', 'setCounter', 0),
  withHandlers({
    increment: props => () => props.setCounter(n => n + 1),
    decrement: props => () => props.setCounter(n => n - 1)
  })
)

const enhance = compose(
  withState('counter', 'setCounter', 0),
  withProps(({ setCounter }) => ({
    increment: () => setCounter(n => n + 1),
    decrement: () => setCounter(n => n - 1)
  }))
)

【问题讨论】:

    标签: reactjs recompose


    【解决方案1】:

    这主要与性能有关,因为withHandlers 不会在每次渲染时创建一个新函数。来自related Github issue

    withProps 每次更新时都会创建新函数;在 另一方面,withHandlers 不会创建新函数。

    withHandlers 在您想将这些函数传递给其他函数时很有用 shouldComponents 通过比较 props 实现的组件 浅浅(就像recompose/pure 做的那样)。

    【讨论】:

      【解决方案2】:

      除了 Fabian Schultz 的回答,请注意 withProps 可用于添加任何类型的道具,而 withHandlers 只能添加功能。

      因此,当您添加功能时,请尽可能使用withHandlers,以提高性能。添加其他内容时,请使用withProps(如果您想删除所有其他道具,请使用mapProps)。

      【讨论】:

        猜你喜欢
        • 2018-02-22
        • 2017-06-01
        • 2018-02-05
        • 2017-10-13
        • 2018-02-14
        • 2017-12-24
        • 2019-10-02
        • 2017-08-15
        • 2018-01-22
        相关资源
        最近更新 更多