首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在React的recompose的生命周期方法中setState?

如何在React的recompose的生命周期方法中setState?
EN

Stack Overflow用户
提问于 2017-01-14 22:53:19
回答 1查看 4.7K关注 0票数 15

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

这是一个很棒的库。我使用compose实用程序作为容器组件,将状态作为道具向下传递给表示组件,如下所示:

代码语言:javascript
复制
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: () => {
      ...

注意componentDidMount中的setIsReady(true)调用。这就是我想要做的,但是lifecycle/componentDidMount不能访问setIsReady。如何通过recompose实现从componentDidMount更新状态的预期结果?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-15 00:00:31

我发现如果将lifecycle方法移到withState方法之后,就可以通过访问this.props.setterFunction来访问setter方法。在我的例子中,这是我正在寻找的解决方案:

代码语言:javascript
复制
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: () => {
      ...
票数 18
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41651283

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档