gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:14:46 28 4
gpt4 key购买 nike

我有一个 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com