TypeError:无法读取axios响应中未定义的属性'setState'在React JS中获取数据

时间:2018-08-13 07:39:36

标签: javascript reactjs axios

我正在尝试使用api结果放置自动建议。

import React, { Component } from "react";
import Autosuggest from "react-autosuggest";
import axios from "axios";

// When suggestion is clicked, Autosuggest needs to populate the input
// based on the clicked suggestion. Teach Autosuggest how to calculate the
// input value for every given suggestion.
const getSuggestionValue = suggestion => suggestion.city;

// Use your imagination to render suggestions.
const renderSuggestion = suggestion => <div>{suggestion.city}</div>;

class Autocomplete extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "",
      suggestions: []
    };
    this.getData = this.getData.bind(this);
  }

  onChange = (event, { newValue }) => {
    this.setState({
      value: newValue
    });
  };

  getData(value) {
    var itemslist = {};
    axios
      .get(
        "https://abcdgf/api/cities?page=1&perPage=1000&search=" +
          value
      )
      .then(function(response) {
        console.log(response.status);
        if (response.status === 200) {
          itemslist = response.data.data;
          console.log(itemslist);
          this.setState({
            suggestions: itemslist.filter(
              lang => lang.city.toLowerCase().slice(0, value.length) === value
            )
          });
        }
      })
      .catch(function(error) {
        console.log(error);
      });
  }

  // Autosuggest will call this function every time you need to update suggestions.
  // You already implemented this logic above, so just use it.
  onSuggestionsFetchRequested = ({ value }) => {
    if (value.length > 2) {
      this.getData(value.trim().toLowerCase());
    }
  };

  // Autosuggest will call this function every time you need to clear suggestions.
  onSuggestionsClearRequested = () => {
    this.setState({
      suggestions: []
    });
  };

  render() {
    const { value, suggestions } = this.state;

    // Autosuggest will pass through all these props to the input.
    const inputProps = {
      placeholder: "Type a programming language",
      value,
      onChange: this.onChange
    };

    // Finally, render it!
    return (
      <Autosuggest
        suggestions={suggestions}
        onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
        onSuggestionsClearRequested={this.onSuggestionsClearRequested}
        getSuggestionValue={getSuggestionValue}
        renderSuggestion={renderSuggestion}
        inputProps={inputProps}
      />
    );
  }
}
export default Autocomplete;

在getData函数的第49行,它给出了一条错误消息,表明无法读取未定义的属性'setState'。实际上,getData是在构造函数中声明的。如果我删除此axios,则说明它工作正常。请让我知道这是什么错误。预先感谢。

1 个答案:

答案 0 :(得分:0)

然后使用箭头功能或将其绑定

then((response) => {
    console.log(response.status);
    if (response.status === 200) {
      itemslist = response.data.data;
      console.log(itemslist);
      this.setState({
        suggestions: itemslist.filter(
          lang => lang.city.toLowerCase().slice(0, value.length) === value
        )
      });
    }
  })

因为其中的函数是稍后将被调用的回调,并且在正常函数(非箭头函数)的情况下,它指向调用该函数的对象,因此该内部回调不会指向您的AutoComplete类对象,这就是为什么您遇到错误