【发布时间】:2018-03-31 08:14:52
【问题描述】:
tl;dr:this.setState({ results: body.hits.hits }); 不起作用
我需要在 React.js v16 中呈现来自 ElasticSearch 索引的响应。我确实有 React v
用 ES6 类语法重写后我打破了:
class App extends Component {
constructor(props) {
super(props)
this.state = { results: [] };
}
handleChange(event) {
const search_query = event.target.value;
client.search({
index: _index,
type: _type,
body: {
query: {
multi_match: {
query: search_query,
fields: ['title^100', 'tags^100', 'abstract^20', 'description^10', 'chapter^5', 'title2^10', 'description2^10'],
fuzziness: 1,
},
},
},
}).then(function(body) {
this.setState({ results: body.hits.hits });
}.bind(this),
function(error) {
console.trace(error.message);
}
);
}
render() {
return (
<div className="container">
<input type="text" onChange={this.handleChange} />
<SearchResults results={this.state.results} />
</div>
);
}
}
我正在使用 App 组件将 initialState results 设置为构造函数内的空数组。然后使用 handleChange 函数从输入字段中获取文本输入并将它们作为搜索查询发送到 ES。这可行,我可以看到 body.hits.hits 的控制台跟踪,看起来像这样:
TRACE: 2017-10-19T09:35:37Z
-> POST http://localhost:9200/myIndex_2017_09_09/article/_search
{
"query": {
"multi_match": {
"query": "query",
"fields": [
"title^100",
"tags^100",
"abstract^20",
"description^10",
"chapter^5",
"title2^10",
"description2^10"
],
"fuzziness": 1
}
}
}
<- 200
{
"took": 19,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 369,
"max_score": 18.169382,
"hits": [
{
"_index": "myIndex_2017_09_09",
"_type": "article",
"_id": "AV5mDaz7Jw6qOfpXAp1g",
"_score": 18.169382,
"_source": {
"title2": "title2",
"series": [
"series1",
"series2",
"series3"
],
"models": [
"models1",
"models2"
],
"description": "description",
"description2": "description2",
"link": "URL",
"title": "title",
"chapter": "chapter",
"tags": [
"tags1",
"tags2",
"tags3"
],
"image": "URL",
"abstract": "abstract"
}
}
]
}
}
然后我添加了一个渲染函数来显示输入字段和另一个无状态组件 SearchResults 来在响应上迭代一些 JSX。这个组件是传递下来的this.state.results,它不似乎工作:
const SearchResults = ({results}) => (
<div className="search_results">
<hr />
<table>
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody>
{results.map((result , i) =>
<ResultRow key={i}
title={result._source.title2} />
)}
</tbody>
</table>
</div>
)
const ResultRow = ({ title }) => (
<tr>
<td>
{title}
</td>
</tr>
)
SearchResults 的状态始终显示为空数组。但是,当我向 App 构造函数添加一些虚拟数据时,效果会很好:
constructor(props) {
super(props)
this.state = { results: [
{
"_index": "myIndex_2017_09_09",
"_type": "article",
"_id": "AV5mDXcSJw6qOfpXAp0a",
"_score": 5.5604653,
"_source": {
"title2": "title 01",
}
},
{
"_index": "myIndex_2017_09_09",
"_type": "article",
"_id": "AV5mDXcSJw6qOfpXApsa",
"_score": 2.1404631,
"_source": {
"title2": "title 02",
}
}
]}
}
有人能发现错误吗?
【问题讨论】:
标签: javascript json reactjs elasticsearch es6-class