【问题标题】:Which way do props flow with compose()?props 使用 compose() 以哪种方式流动?
【发布时间】:2018-01-25 15:35:33
【问题描述】:

考虑以下几点:

const Foo = defaultProps({
        foo: "foo"
});

compose(
    Foo,
    LoadJson,
    RunParser
)(Bar);

在这种情况下,foo 的 prop 是否会向下流经 LoadJson->RunParser->Bar?还是逆序,foo 流经RunParser->LoadJson->Bar

有没有更好的方法来从概念上设想这个而不是像那样的线性流?

【问题讨论】:

  • 在文档中它说Composes functions from right to left.,所以我会说它类似于RunParser(LoadJson(Foo(Bar)));。见compose()
  • 谢谢!这有助于函数调用的顺序,尽管我仍然对 props 的流动方式有些困惑。

标签: reactjs recompose


【解决方案1】:

如您所见here,道具从左到右流动,这意味着在左侧定义的道具对右侧的 HOC 可见。因此,在您的情况下,LoadJson 和 RunParser 应该会看到 prop foo

const enhance = compose(
    withProps({
    offset: 10,
  }),
  withState('count', 'updateCount', 0),
  withHandlers({
    increment: props => () => props.updateCount(n => n + 1 + props.offset),
    decrement: props => () => props.updateCount(n => n - 1)
  })
)

const Counter = enhance(({ count, increment, decrement }) =>
    <div>
    Count: {count}
    <div>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </div>
  </div>
)

【讨论】:

    猜你喜欢
    • 2012-07-17
    • 2015-09-12
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 2023-03-10
    • 2020-01-21
    • 1970-01-01
    相关资源
    最近更新 更多