javascript - 无法读取未定义的属性 setState

标签 javascript reactjs undefined state

我有一个 react 组件,它有一个带有 axios 调用的函数来检索数据。 该数据被放入一个数组中,然后该数组被发送到状态。

但是,在尝试设置时出现错误: 无法读取未定义的属性“setState”

我在构造函数中绑定(bind)了函数,setState 在 axios 调用之外。

我的代码:

import * as React from "react";
import * as ReactDOM from "react-dom";

import axios from "axios";
import { host } from "../../searchkitConfig/const_host.js";

import {
  SearchkitComponent
} from "searchkit";

export class AutoCompleteContainer extends SearchkitComponent {
  constructor(props){
    super(props);
    this.state = {
      "suggestCallReady" : false,
      "suggestions":[]
    };
    this.suggestCall = this.suggestCall.bind();
  }
  suggestCall(){
    const query =
    {
      "_source": [
        "suggest-auteur"
      ],
      "suggest": {
        "auteur_suggest": {
          "prefix": "te",
          "completion": {
            "field": "suggest-auteur"
          }
        },
        "hoofdtitel_suggest": {
          "prefix": "te",
          "completion": {
            "field": "suggest-hoofdtitel"
          }
        },
        "imprint_suggest": {
          "prefix": "te",
          "completion": {
            "field": "suggest-imprint"
          }
        }
      }
    };

    var suggestArray = [];
    axios
      .post(host + "/_search", query, {
        headers: {
          "Content-Type": "application/json"
        }
      })
      .then( res => {
        for(var i = 0; i < res.data.suggest.auteur_suggest[0].options.length; i++){
          suggestArray.push(res.data.suggest.auteur_suggest[0].options[i].text);
        }

      });
      console.log('suggestArray:',suggestArray)
      this.setState({"suggestions":suggestArray});
  }
  componentDidMount(){
    this.suggestCall();
  }
  render(){
    return(
      <div>{this.state.suggestions.length >1 ? this.state.suggestions : "No suggestions has been found"}</div>
    )
  }
}

enter image description here

最佳答案

this.suggestCall = this.suggestCall.bind(this);

你需要在bind函数中传递this

关于javascript - 无法读取未定义的属性 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53775723/

相关文章:

javascript - Bootstrap collapse 有一个跳跃的过渡

c# - 每次使用innerHTML或jquery html()渲染页面的一部分时如何防止页面滞后/挂起

javascript - react : How do you write id to have dynamic axios requests

Javascript 和非常长的字符串

javascript - 使用 Angular 动态生成的选择选项未选择默认值

reactjs - 无法在 react 中编译

javascript - 如何在 native react 中限制文本字段的退格事件

javascript - React-router 在应用中找不到其他页面的组件

postgresql - 在将 Rails 数据存储到 Postgres 间隔数据类型列之前,形成 Rails 数据的正确方法是什么?

c++ - 链接器错误 : undefined reference c++