我正在使用 React 为搜索引擎开发 UI。对于搜索,我使用 Elasticsearch。我能够连接并从索引中获取结果,但我只能获取我指定大小的结果数量。我想启用无限滚动,直到客户端到达结果末尾。
我需要帮助来实现扫描、滚动和分页
这是我的app.js组件代码
import React from 'react';
import Header from './header';
import Footer from './footer';
import SearchResults from './searchresults';
import elasticsearch from 'elasticsearch';
let client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
})
class App extends React.Component {
constructor(props) {
super(props);
this.state = { results: [], search_query: '*' }
this.handleChange = this.handleChange.bind(this);
}
handleChange ( event ) {
var search_query = event.target.value;
var size = 20;
client.search({
index: 'photos',
type: 'photo',
q: search_query,
size: size
}).then(function ( body ) {
this.setState({ results: body.hits.hits })
}.bind(this), function ( error ) {
console.trace( error.message );
});
}
render () {
return (
<div className="main">
<Header />
<div className="row test">
<div className="col-xs-4"></div>
<div className="col-xs-4">
<div className="row">
<div className="col-xs-12">
<input id="search" className="form-control" type="text" placeholder="Start Searching" name="search" onChange={ this.handleChange }></input>
</div>
</div>
</div>
<div className="col-xs-4"></div>
<br />
</div>
<div className="test bclass">
<SearchResults results={ this.state.results } />
<button type="button" className="btn btn-default">Load More</button>
</div>
<Footer />
</div>
)
}
}
export default App;
这是我的 searchresults.js 组件代码:
import React from 'react';
import PropTypes from 'prop-types';
import LazyLoad from 'react-lazy-load';
let i = 1;
class SearchResults extends React.Component {
constructor(props) {
super(props);
this.state = { results: [] }
}
render () {
return (
<div className="search_results">
<hr />
<ul>
{ this.props.results.map((result) => {
return (
<li key={ result._id + i++}>
<LazyLoad className="lazy">
<img className="image" src={result._source.file_name} alt="Search Result" />
</LazyLoad>
</li>
) }) }
</ul>
</div>
)
}
}
SearchResults.propTypes = {
results: PropTypes.array
}
export default SearchResults;
最佳答案
像 Facebook 主页一样使用 AJAX 滚动调用;使用全局递增的 counterVariable
,该变量在 ElasticSearch 的每次 AJAX 调用上递增,参数来自
您希望在一个 AJAX 中使用的大小
结果文档的记录卷轴的召唤。每次 ajax 调用时都会增加。
关于滚动调用AJAX的javaScript,请参阅Similar Solved Answer .
关于javascript - 如何获得无限滚动,直到所有结果都显示在React中的Elasticsearch JS API中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44299141/