小编典典

我该如何在React的recompose的生命周期方法中设置setState?

reactjs

我在我的React项目https://github.com/acdlite/recompose/中使用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。这是我想要做的,但是lifecycle /
componentDidMount没有访问权限setIsReady。如何完成componentDidMount通过recompose
更新状态的预期结果?


阅读 303

收藏
2020-07-22

共1个答案

小编典典

好吧,我发现如果您在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: () => {
      ...
2020-07-22