reactjs - 无法从 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();
}
}
解决方案
这就是静态函数的目的。它无法访问实例 ( 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 的上下文来管理共享状态。
推荐阅读
- reactjs - 使用 NPM 安装 stencil 组件,其方法不能直接在 react 中使用。js和vue。js
- jenkins - 名称中有斜线的分支的多分支管道作业存在问题
- java - 对 BufferedImage 应用抗锯齿
- bash - 如何使用 grep 和 sed 从仅包含国家/地区的 html 文件中获取列表?
- dns - DNS Records and Nameservers
- php - 试图在 symfony 中获取非对象的属性
- vba - Is there a method to use VBA to insert multiple images and insert them in order of selection through the dialog box?
- javascript - Pseudo element :after not displaying
- python - 从循环中返回所有数据
- docker - Docker compose:Traefik 和 Docker 注册表