【问题标题】:Getters in ES6 functional component React.jsES6 功能组件 React.js 中的 Getter
【发布时间】:2019-12-07 15:28:23
【问题描述】:

我在 React 中使用无状态组件,但发现使用 Getters 存在问题。

对于 statefull 组件(基于类的组件),它可以正常工作,但是我如何在无状态(功能组件)中使用它;

 // this is code for statefull component(class based component)

get lookupsOfSelectedGroup(){
        const lookUps = this.props.mainLookups.filter(
          item => item.extras.parent === this.state.activeGroup
        );

        if (lookUps[0] && lookUps[0].responseStatus === 200) {
          return lookUps[0].response.lookup;
        }

        return [];
  }


// this is the code for functional component I did:

    get lookupsOfSelectedGroup =()=> {
        const lookUps = this.props.mainLookups.filter(
          item => item.extras.parent === this.state.activeGroup
        );

        if (lookUps[0] && lookUps[0].responseStatus === 200) {
          return lookUps[0].response.lookup;
        }

        return [];
      }    ```

Cannot find name 'get'.

【问题讨论】:

  • 你试过get lookupsOfSelectedGroup(){ ... }
  • 无状态组件没有实例,你希望如何调用这个getter?此外,您的 get lookupsOfSelectedGroup = arrow function 即使对于基于类的组件也不起作用。

标签: javascript reactjs getter-setter getter


【解决方案1】:

您只能在 ES6 类和对象字面量中使用 getset 关键字。

Check the reference.

【讨论】:

    【解决方案2】:

    getter 只能定义为对象或类的属性。您不能直接在函数体中定义它们。

    您要么需要将lookupsOfSelectedGroup 替换为普通函数(可能是更好的解决方案),要么将其包装在对象字面量中。

    【讨论】:

      猜你喜欢
      • 2016-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 2021-12-09
      • 2021-08-11
      相关资源
      最近更新 更多