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

发布于 2021-01-31 22:43:43

我在我的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
更新状态的预期结果?

关注者
0
被浏览
88
1 个回答
  • 面试哥
    面试哥 2021-01-31
    为面试而生,有面试问题,就找面试哥。

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


推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看