Uncaught (in promise) TypeError: this.loadCategories is not a function in React

时间:2021-07-27 02:41:17

标签: javascript reactjs

我正在做一个 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;

1 个答案:

答案 0 :(得分:3)

正如 rogers 先生所说,问题是关于 bindthis

如果您使用的是类组件,您可以使用 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 });
 }
}