首页 > 解决方案 > 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;

标签: javascriptreactjs

解决方案


正如罗杰斯先生评论的那样,这个问题是关于bindthis

如果您使用的是类组件,您可以使用 ES6 语法来“自动绑定”

async loadCategories() {
    const categories = await getCategories();
    this.setState({ categories });
}

将会

const loadCategories = async () => {
    const categories = await getCategories();
    this.setState({ categories });
}

使用箭头函数并将其应用于类上的常量将确保绑定this.

另一种方法是,如果您仍想在类中使用相同的函数语法,您可以使用bindAlllodash手动绑定构造函数上的函数。

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 });
 }
}

推荐阅读