WithProps 与 withHandlers
WithProps vs withHandlers
我一直在看react recompose library 并试图抓住这里的区别,结果是一样的,试图阅读文档,但更加困惑,为什么有两种方法可以做同样的事情?
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)
}))
)
这主要与性能有关,因为 withHandlers
不会在每次渲染时都创建一个新函数。来自 related Github issue:
withProps
will create new functions every time when it get updated; on
the other hand, withHandlers
won't create new functions.
withHandlers
is useful when you want to pass these functions to other
components which shouldComponents
are implemented by comparing props
shallowly (like how recompose/pure
do).
除了 Fabian Schultz 的回答,请注意 withProps
可用于添加任何类型的道具,而 withHandlers
只能添加功能。
因此,当您添加函数时,请尽可能使用 withHandlers
以提高性能。当你添加任何其他东西时,使用 withProps
(如果你想删除所有其他道具,则使用 mapProps
)。
我一直在看react recompose library 并试图抓住这里的区别,结果是一样的,试图阅读文档,但更加困惑,为什么有两种方法可以做同样的事情?
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)
}))
)
这主要与性能有关,因为 withHandlers
不会在每次渲染时都创建一个新函数。来自 related Github issue:
withProps
will create new functions every time when it get updated; on the other hand,withHandlers
won't create new functions.
withHandlers
is useful when you want to pass these functions to other components whichshouldComponents
are implemented by comparing props shallowly (like howrecompose/pure
do).
除了 Fabian Schultz 的回答,请注意 withProps
可用于添加任何类型的道具,而 withHandlers
只能添加功能。
因此,当您添加函数时,请尽可能使用 withHandlers
以提高性能。当你添加任何其他东西时,使用 withProps
(如果你想删除所有其他道具,则使用 mapProps
)。