我有一系列数据,这些数据在一个数组(json文件)中包含一些对象,它将由react显示。
class App extends React.Component {
constructor(props){
super(props);
this.state = {
data: [],
.
.
.
currentPage: 1,
itemsPerPage: 20,
value: '',
filterTerm: null,
startIndex : 0,
endIndex : 4,
}}}
[{'id': '5c0b6cd9e1382352759fbc25', 'hotelinfo': {'hotelsearch': {'realname': 'Korston Hotel Moscow'}},{'id': '5c0b6cd9e1382352759fbc24', 'hotelinfo': {'hotelsearch': {'realname': 'Lavanta Hotel'}},{'id': '5c0b6cd9e1382352759fbc28', 'hotelinfo': {'hotelsearch': {'realname': 'Stanpoli Hotel'}}]
有一个分页,默认情况下显示4页,然后单击下一步按钮显示其余页面。
render() {
const { data, currentPage, itemsPerPage, startIndex, endIndex } = this.state;
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = data.slice(indexOfFirstItem, indexOfLastItem);
const renderHotel = currentItems.sort((a, b) => a.total - b.total).filter(this.filterData).map((item, i) => {
return <div class="item">
<span>{item.hotelinfo.hotelsearch.realname}</span>
</div>
});
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(data.length / itemsPerPage); i++) {
pageNumbers.push(i);
}
const renderPageNumbers = pageNumbers.slice(startIndex, endIndex).map(number => {
return (
<li className={(this.state.currentPage === number ? 'active ' : '') + 'controls'}
key={number}
id={number}>
{number}
</li>
)
});
return (
<div>
<input type="text" value={this.state.value}
onChange={this.handleInputChange} class="hotelName" />
<span onClick=this.handleSearch} class="searchbtn">search</span>
{ renderHotel }
<ul id="page-numbers" class="pagenumDef">
<li onClick={this.decremant} class="nexprev">
<span class="fa-backward"></span></li>
{renderPageNumbers}
<li onClick={this.increment} class="nexprev"><span class="fa-forward"></span></li>
</ul>
</div >
)
};
我有一个输入(class =“ hotelName”),用户开始输入该内容(例如,用户类型'Korston'),然后单击一个按钮,新结果应仅包含那些包含“ Korston”名称的酒店的数据。 / p>
handleInputChange(event) {
this.setState({ value: event.target.value });
}
handleSearch = () => {
let inputval = this.state.value
const { value } = this.state;
this.setState({ filterTerm: value });
}
filterData = (item) => {
const { filterTerm: term } = this.state;
if (term === null) {
return true;
}
let inputval = this.state.value
inputval = term.toLowerCase()
.split(' ')
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(' ');
let realname = item.hotelinfo.hotelsearch.realname
let len = realname.length
if (len !== 0) {
if (realname.includes(inputval)) {
return true
} else {
return false
}
}
return false;
}
主要问题是,每次我仅过滤当前页面时,这意味着我过滤了分页结果。我应该先过滤列表,然后再对过滤后的列表进行分页,但是我该怎么做呢?
答案 0 :(得分:0)
答案 1 :(得分:0)
尝试在切片示例之前使用this.state.value过滤数据:
var targetData = data;
if (this.state.value) {
targetData = data.filter((d) => d.hotelinfo.hotelsearch.realname.toLowerCase().indexOf(this.state.value.toLowerCase()) >= 0);
}
const currentItems = targetData.slice(indexOfFirstItem, indexOfLastItem);