代码之家  ›  专栏  ›  技术社区  ›  FabricioG

无法绑定到导入的函数。错误未定义

  •  0
  • FabricioG  · 技术社区  · 6 年前

    我目前在导入模块和在React中使用它时遇到问题。有人问过这个问题,我试过我读过的答案,但什么也没有。我不知道我做错了什么。

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

    错误是它无法将此绑定到未定义,因为PullProductDetails未定义。

    我也尝试过:

    export const pullProductDetails = () => {}
    

    以上都不起作用。我需要从app.js中调用this.pullproductdetails。有什么想法吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Bilal    6 年前

    你必须在作业的右边省略这个

    this.pullProductDetails = pullProductDetails.bind(this);
    

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

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