【问题标题】:How to get props on recompose lifecycle without using `this`?如何在不使用`this`的情况下获得重组生命周期的道具?
【发布时间】:2017-12-03 01:11:12
【问题描述】:

我正在使用eslint-plugin-immutable 所以我不能使用this 关键字(我可以使用eslint-disable-line,但我不想),所以我想知道@ 是否有任何方法987654323@ 访问任何挂载生命周期内的道具,而不使用 this 关键字。

const enhance = compose(
  lifecycle({
    componentWillMount() {
      const { props } = this // throws eslint error
      console.log(this.props); // works, throws eslint error
    },
  }),
);

【问题讨论】:

  • 为什么 eslint 会抱怨 referencesthis?在 JavaScript 中你基本上无法绕过this;它是对象模型的基础。
  • eslint-plugin-immutable的Beucase,有个规则叫no-this
  • 就像我说的,如果你正在使用 JavaScript 原型代码,那么很难绕过对 this 的引用;它基本上使使用这样的代码变得不可能或充其量是毫无意义的。
  • 也许你是对的。但这不是重点,只是想知道这是否可能。这并不意味着我会这样做。
  • 阅读该插件的文档,它明确地试图强迫你以特定的风格编写代码。如果您不想那样编写代码,请不要使用我猜的插件。

标签: javascript reactjs lifecycle recompose


【解决方案1】:

如果不使用lifecycle 中的this 关键字,就无法访​​问props。 如果你经常有相同的功能需要使用生命周期方法,你可以实现自己的HOC,仍然要使用this,但除此之外你不必写this,如recompose/shouldUpdate

【讨论】:

    【解决方案2】:

    您可以使用专门为此目的编写的with-lifecycle HOC。你的例子:

    import withLifecycle from '@hocs/with-lifecycle';
    
    const enhance = compose(
        withLifecycle({
            onWillMount(props) {
                console.log(props);
            },
        }),
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 2017-05-31
      • 2018-04-02
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多