【发布时间】:2018-12-14 08:12:14
【问题描述】:
我有一个反应组件,它有一个带有 axios 调用的函数来检索数据。 该数据正在被放入一个数组中,并且该数组正在发送到该状态。
但是,在尝试设置时出现错误: 无法读取未定义的属性“setState”
我已经在构造函数中绑定了函数,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>
)
}
}
【问题讨论】:
-
this.suggestCall = this.suggestCall.bind(this);你需要在bind函数中传递this -
哦,哈哈..那太愚蠢了。非常感谢。
-
其实你甚至不需要绑定它。但是您还有另一个问题:由于您在
then回调之外调用setState,它不会将状态设置为您获取的数据。将setState移动到then内。
标签: javascript reactjs undefined state