首页 > 解决方案 > 无法绑定到导入的函数。错误未定义

问题描述

我目前在导入模块并在反应中使用它时遇到问题。有人问过这个问题,我已经尝试过我读过的答案,但没有。我不确定我做错了什么。

在 App.js 我导入这个:

import { pullProductDetails } from './GetDetails';

在 GetDetails.js 我有这个:

export default pullProductDetails = () => {
      this.setState({isLoading: true});
      fetch('http://127.0.0.1:8000/product_details/fetch/36')
      .then(response => response.json())
      .then(json => {
        const quantityDetails = json.productQuanties.map((quantityDetail) => {
            quantityDetail.selected = false;
            quantityDetail.title = "Quantity";
        });
        this.setState(
          {
            quantityProduct: [...this.state.quantityProduct, ...json.productQuanties],
            isLoading: false,
          }, () => this.dropdownCounter()
        );
          });
    }

然后在 app.js 中绑定它,这样我就可以使用“this”

this.pullProductDetails = this.pullProductDetails.bind(this);

错误是它无法将 this 绑定到 undefined,因为 pullProductDetails 是未定义的。

我也试过这个:

export const pullProductDetails = () => {}

以上都不起作用。我需要从我的 App.js 调用 this.pullProductDetails。有任何想法吗?

标签: reactjs

解决方案


您必须省略作业右侧的 (this)

this.pullProductDetails = pullProductDetails.bind(this);

因为你绑定的函数不是当前组件的函数。pullProductDetails 的定义也不应该是箭头函数,因为在箭头函数中 this 的上下文总是指向函数的定义位置。

获取详细信息.js:

export function pullProductDetails(){
  this.setState({isLoading: true});
  fetch('http://127.0.0.1:8000/product_details/fetch/36')
  .then(response => response.json())
  .then(json => {
    const quantityDetails = json.productQuanties.map((quantityDetail) => {
        quantityDetail.selected = false;
        quantityDetail.title = "Quantity";
    });
    this.setState(
      {
        quantityProduct: [...this.state.quantityProduct, ...json.productQuanties],
        isLoading: false,
      }, () => this.dropdownCounter()
    );
      });
}

在您的主文件中:

import pullProductDetails from './GetDetails';

然后添加构造函数:

constructor(props){
  super(props);
  this.pullProductDetails = pullProductDetails.bind(this);
}

推荐阅读