我正在尝试显示我在为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: {"text": "new"}
},
}
}, 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>
);
}
}
答案 0 :(得分:0)
在您的代码中,您需要为每次迭代更新状态中的结果, 尝试更新状态如下:
this.setState({
results: response.hits.hits.map(hit =>
({ text: hit._source.text, userId: hit._source.user_id })
)
});
只需使用简单的地图消费它:
results.map(result => (
<li key={result.userId}>{result.text}</li>
));
如果它不起作用或仍然出错,请给我更多代码, 我可以跑的东西?
<强>更新强> 我认为elasticsearch客户端以某种方式丢失了这个上下文,但这在我的机器上工作,我已经使用了 async / await 方法试试看:
export default class Search extends Component {
constructor(props) {
super(props);
this.state = {
searched: false,
results: []
};
}
handleChange = async event => {
const search_query = event.target.value;
const response = await client.search({ q: search_query });
this.setState({
searched: true,
results: response.hits.hits.map(item => ({
userId: item._source.user_id,
text: item._source.text
}))
});
};
render() {
const { searched, results } = this.state;
return (
<div>
<input
className={'search-bar'}
type="text"
onChange={this.handleChange}
/>
<DisplayResult searched={searched} results={results} />
{/*<button className={"button"}><Search /></button>*/}
</div>
);
}
}
这是DisplayResult组件:
import React, { Component } from 'react';
const renderResult = results =>
results.map(result => <li key={result.userId}>{result.text}</li>);
export default class DisplayResult extends Component {
render() {
const { searched, results } = this.props;
return (
<div className="search_results">
<hr />
{results.length > 0 ? (
<ul>{renderResult(results)}</ul>
) : searched && (
<h1>there is no result</h1>
)}
</div>
);
}
}