javascript - Uncaught (in promise) TypeError: this.loadCategories is not a function in React
问题描述
我正在做一个 React 应用程序。
这是我的代码。为什么我在 handleCategoryUpdated 函数中出现错误?
categoryManager.jsx:22 Uncaught (in promise) TypeError: this.loadCategories 不是一个函数。
import React, { Component } from "react";
import { getCategories } from "../services/categoriesService";
import CategoryCard from "./categoryCard";
import CategoryEditor from "./categoryEditor";
class CategoryManager extends Component {
state = {
categories: [],
};
async componentDidMount() {
await this.loadCategories();
}
async loadCategories() {
const categories = await getCategories();
this.setState({ categories });
}
async handleCategoryUpdated() {
await this.loadCategories();
}
render() {
const { categories } = this.state;
return (
<div>
<h1>Categories</h1>
<CategoryEditor onCategoryUpdated={this.handleCategoryUpdated} />
<div style={{ marginTop: "50px" }}>
{categories.map((category, index) => (
<CategoryCard category={category} key={index} />
))}
</div>
</div>
);
}
}
export default CategoryManager;
解决方案
正如罗杰斯先生评论的那样,这个问题是关于bind
的this
。
如果您使用的是类组件,您可以使用 ES6 语法来“自动绑定”
async loadCategories() {
const categories = await getCategories();
this.setState({ categories });
}
将会
const loadCategories = async () => {
const categories = await getCategories();
this.setState({ categories });
}
使用箭头函数并将其应用于类上的常量将确保绑定this
.
另一种方法是,如果您仍想在类中使用相同的函数语法,您可以使用bindAll
或lodash
手动绑定构造函数上的函数。
import _ form 'lodash';
class CategoryManager {
constructor() {
this.state = {
categories: [],
};
// You can either use lodash here or manual bind
_.bindAll(this, ['loadCategories']);
// Or use manual bind
this.loadCategories = this.loadCategories.bind(this);
}
async loadCategories() {
const categories = await getCategories();
this.setState({ categories });
}
}
推荐阅读
- spring - Kotlin 中的泛型方法无法识别类型
- ios - 从json获取数据,但我的数据不是数组,swift 3
- python-3.x - 如何在简单的数学运算中定义 keras 自定义损失函数
- java - 在 mvn 包之后缺少 resteasy 提供程序
- java - 如何基于 API 循环 CardView
- numpy - 最多 2 个 numpy unint8 数组
- html - 如何动态更改 ngStyle?
- amazon-web-services - 如果 AWS ElastiCache Redis 内存已满,会发生什么?
- python - flake8 - 带有 python3 元类参数的 E999 语法错误
- node.js - 如何在nodejs中编写复杂的json格式