如何在React的recompose的生命周期方法中设置state? [英] How do I setState within React's recompose's lifecycle method?

查看:105
本文介绍了如何在React的recompose的生命周期方法中设置state?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using recompose in my React project https://github.com/acdlite/recompose/

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

It's a great library. I'm using the compose utility as a container component that passes state down as props to the presentational component like so:

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 。如何从 componentD完成更新状态的预期结果idMount 重组?

Note the setIsReady(true) call within componentDidMount. This is what I want to do, however lifecycle/componentDidMount doesn't have access to setIsReady. How can I accomplish my intended result of updating state from componentDidMount with recompose?

推荐答案

我发现你是否移动了 withState 方法之后的生命周期方法,您可以通过访问 this.props.setterFunction 。在我的例子中,这是我正在寻找的解决方案:

Well I found out if you move the lifecycle method after the withState methods, you have access to the setters by accessing this.props.setterFunction. In my case, here is the solution I was looking for:

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: () => {
      ...

这篇关于如何在React的recompose的生命周期方法中设置state?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆