WithProps vs withHandlers

Pol*_*sas 5 reactjs 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)
  }))
)
Run Code Online (Sandbox Code Playgroud)

Fab*_*ltz 9

它主要与性能有关,因为withHandlers不会在每次渲染时创建新函数.来自相关的Github问题:

withProps每次更新时都会创建新功能; 另一方面,withHandlers不会创建新功能.

withHandlers当你想要将这些函数传递给其他组件时很有用,这些组件shouldComponents是通过浅浅地比较props来实现的(比如怎么recompose/pure做).


Gre*_*reg 7

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

因此,添加功能withHandlers时,请尽可能使用以提高性能。当您添加其他任何东西时,请使用withProps(或mapProps如果您要删除所有其他道具)。