【发布时间】:2017-11-03 12:13:18
【问题描述】:
我正在为搜索引擎(使用 elasticsearch)构建一个 UI(使用 ReactJs),它每页返回 20 个结果。 当我单击下一步按钮时,它会给出下一个 20 个结果,但旧结果会被新结果替换。我想要的只是将新结果附加到旧结果中。
这是我的代码:
import React from 'react'
import SearchResults from './searchresults';
import elasticsearch from 'elasticsearch';
let client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
})
var size = 20;
var from_size = 0;
var search_query = '*'
class Searchbox extends React.Component {
constructor(props) {
super(props);
this.state = { results: [], notFound: true }
this.handleChange = this.handleChange.bind(this);
this.next = this.next.bind(this);
this.prev = this.prev.bind(this);
this.er = this.er.bind(this);
this.esSearch = this.esSearch.bind(this);
}
componentWillMount() {
search_query = '*';
this.esSearch(search_query, from_size);
}
handleChange ( event ) {
search_query = event.target.value + '*';
from_size = 0;
this.esSearch(search_query, from_size);
}
next() {
from_size += size;
if(from_size<=size) {
console.log(from_size);
console.log(search_query);
this.esSearch(search_query, from_size);
}
else {
this.er();
from_size -= size;
}
}
er() {
alert("NO MORE PAGES");
}
esSearch( sq, from ) {
var search_query = sq;
client.search({
index: 'photos',
type: 'photo',
q: search_query,
size: size,
from: from
}).then(function ( body ) {
if(body.hits.max_score===null) {
this.setState({notFound: true})
}
else {
this.setState({notFound: false})
}
this.setState({ results: body.hits.hits })
}.bind(this), function ( error ) {
console.trace( error.message );
});
}
renderNotFound() {
return <div className="notFound">Not found. Try a different search.</div>;
}
renderPosts() {
return(
<div className="results">
<SearchResults key={this.from_size} results={ this.state.results } />
<button id="prev" type="button" className="btn btn-primary" onClick={this.prev} >Prev</button>
</div>
)
}
render() {
const { notFound } = this.state;
return (
<div>
<input id="search" className="form-control form" type="text" placeholder="Start Searching" name="search" onChange={ this.handleChange }></input>
<div>
{notFound ? this.renderNotFound() : this.renderPosts()}
</div>
</div>
)
}
}
export default Searchbox;
此应用默认显示所有结果。
【问题讨论】:
-
在您的 esSearch 函数中,您正在将结果添加到您的状态中,从而有效地覆盖其中已有的内容。您应该找到一种附加结果的方法。
-
这就是我的问题@VedranMaricevic
标签: javascript reactjs elasticsearch pagination elastic-stack