首页 > 解决方案 > 无法从 React.Component 静态函数中读取未定义的属性“已检查”

问题描述

我有一个 React.Component,我想从许多不同的 React.Component 中调用这个静态函数。

class Categories extends React.Component {
  constructor(props) {
    super(props);
    this.getCheckedCategories = this.getCheckedCategories.bind(this);
    this.state = {
      checked: [],
      unchecked: []
    };
  }

  static getCheckedCategories() {
    return this.state.checked;
  }
}

所以我尝试连接该功能。

import Categories from './product/checkboxes';

class FullWidthGrid extends React.Component {
  constructor(props) {
    super(props);
    this.state = {

    }
  }

  render() {
    const { classes } = this.props;
    const checkedCategories = Categories.getCheckedCategories();
  }
}

标签: reactjsecmascript-6

解决方案


这就是静态函数的目的。它无法访问实例 ( this)。您可以拥有多个类实例,但只有一个静态函数/属性。

作为一种解决方法(取决于您想要做什么),您可以使用静态属性来存储您的状态:

class Categories extends React.Component {
  constructor(props) {
    super(props);
    Categories.state = {
      checked: [],
      unchecked: []
    };
  }

  static getCheckedCategories() {
    return Categories.state.checked;
  }
}

但是它不能使用,setState因为它是一个实例方法。

想象一下当您有多个Categories组件并且每个组件都有不同的选中/未选中类别时的情况。那么Categories.getCheckedCategories()函数会返回什么?

如果您想要共享状态(检查类别),我建议您从组件中提取状态。例如将其存储在父组件中并将其作为道具传递给子组件。或者使用像 redux 这样的状态库。您还可以使用 react 的上下文来管理共享状态。


推荐阅读