15

我在我的 React 项目中使用 recompose https://github.com/acdlite/recompose/

这是一个很棒的图书馆。我将该compose实用程序用作容器组件,将状态作为道具传递给展示组件,如下所示:

const enhance = compose(
  lifecycle({
    componentDidMount() {
      myCall
        .getResponse([productId])
        .then(products => {
          setIsReady(true);
        });
    },
  }),
  withState('isAvailable', 'setIsAvailable', false),
  withState('isReady', 'setIsReady', false),
  mapProps(({
    setIsAvailable,
    setIsReady,
    ...state,
  }) => ({
    onLogoutTouchTap: () => {
      ...

注意setIsReady(true)内的调用componentDidMount。这是我想做的,但是生命周期/componentDidMount 无权访问setIsReady. componentDidMount我怎样才能通过重构来实现我想要的更新状态的结果?

4

1 回答 1

18

好吧,我发现如果你在lifecycle方法之后移动withState方法,你可以通过访问来访问设置器this.props.setterFunction。就我而言,这是我正在寻找的解决方案:

const enhance = compose(
  withState('isAvailable', 'setIsAvailable', false),
  withState('isReady', 'setIsReady', false),
  lifecycle({
    componentDidMount() {
      myCall
        .getResponse([productId])
        .then(products => {
          this.props.setIsReady(true);
        });
    },
  }),
  mapProps(({
    setIsAvailable,
    setIsReady,
    ...state,
  }) => ({
    onLogoutTouchTap: () => {
      ...
于 2017-01-14T16:00:30.880 回答