【发布时间】:2018-01-20 01:15:43
【问题描述】:
我收到 Uncaught TypeError: Cannot read property 'setState' of undefined 在我连接到 Elasticsearch 的 react 项目中。
链接到我的代码: codesandbox.io/s/oq13r4vl2q
我正在尝试显示运行查询以响应 Elasticsearch 获得的结果,但我无法做到这一点。它给出了错误,但是当我在变量中运行相同的查询时,它返回了正确的结果。有人能告诉我如何将结果存储在“结果”数组中以及如何在网页中显示吗? 出现错误:
import React, { Component } from 'react';
import client from './Credentials';
import '../App.css';
import DisplayResult from './DisplayResult';
export default class Search extends Component {
constructor(props) {
super(props);
this.state = {results: []};
}
handleChange(event) {
const search_query = event.target.value;
client.search({
index: 'tweet',
type: 'tweet',
size: 100,
body: {
query: {
match: search_query
},
}
}, function (error, response, status) {
if (error) {
console.log("search error: " + error)
}
else {
console.log("--- Response ---");
// console.log(response);
console.log("--- Hits ---");
response.hits.hits.forEach(function (hit) {
console.log(hit._source.text);
this.setState(results: hit._source.text)
}.bind(this)
)
}
});
}
render() {
return(
<div>
<input className={"search-bar"} type="text" onChange={this.handleChange}>
</input>
<DisplayResult results={this.state.results} />
{/*<button className={"button"}><Search /></button>*/}
</div>
);
}
}
【问题讨论】:
-
错误发生在哪一行?
-
response.hits.hits.forEach(function (hit) { console.log(hit._source.text); this.setState(results: hit._source.text) }.bind(this)
-
检查我的答案,让我知道这是否适合你。
标签: javascript reactjs elasticsearch