reactjs - 对于我的代码,我没有在 reactjs 中获得分页和搜索栏
问题描述
//这是我的代码//
class TableList extends Component {
constructor(props) {
super(props);
//var totalPages = 100 / 10; // 10 page numbers
this.state = {
query: "",
countries: [],
searchString:[],
currentPageNumber: 1,
pageOfItems: [],
totalItems: 4,
itemsPerPage: 10
}
this.onChangePage = this.onChangePage.bind(this);
}
onChangePage(pageOfItems) {
this.setState({ pageOfItems: pageOfItems });
}
handleInputChange = (event) => {
this.setState({
query: event.target.value
},()=>{
this.filterArray();
})
}
handleSelect(number) {
console.log('handle select', number);
this.setState({currentPageNumber: number});
}
componentDidMount() {
const apiUrl = 'https://indian-cities-api-nocbegfhqg.now.sh/cities';
fetch(apiUrl)
.then(res => res.json())
.then(
(result) => {
this.setState({
countries: result,
searchString:result,
currentPageNumber:result.currentPageNumber,
totalItems: result.totalItems,
itemsPerPage: result.itemsPerPage
});
},
)
}
filterArray = () => {
let searchString = this.state.query;
let result = this.state.countries;
if(searchString.length > 0){
result = result.filter(searchString);
this.setState({
result
})
}
}
render() {
const { countries} = this.state;
let totalPages = Math.ceil(this.state.totalItems / this.state.numItemsPerPage);
return(
<div>
<div className="container">
</div>
<h2>countrie List</h2>
<form>
<input type="text" id="filter" placeholder="Search for..." onChange={this.handleInputChange}/>
</form>
<Table>
<Pagination
bsSize="medium"
items={totalPages}
activePage={this.state.currentPageNumber} onSelect={this.handleSelect.bind(this)}/>
<thead>
<tr>
<th>#ID</th>
<th>countrie Name</th>
<th>Code</th>
<th>States</th>
</tr>
</thead>
<tbody>
{countries.map(countrie => (
<tr key={countrie.City}>
<td>{countrie.sno}</td>
<td>{countrie.City}</td>
<td>{countrie.State}</td>
<td>{countrie.District}</td>
</tr>
))}
</tbody>
</Table>
</div>
)
}
}
export default TableList;
//即将到来的错误是 警告:遇到两个孩子使用相同的钥匙,`Wadi`。密钥应该是唯一的,以便组件在更新时保持其身份。非唯一键可能会导致子项被复制和/或省略 - 该行为不受支持,并且可能在未来版本中更改
解决方案
简而言之:
搜索 - 存储的过滤数据
this.state.result
- 不用于渲染this.setState({ result })
as
{ result }
is a short of{ result: result }
and this good ... 覆盖this.state.countries
会导致源数据丢失(需要重新获取)render
获取/利用this.state.countries
- 始终完整的数据集,不按搜索过滤,不按页面范围划分您需要
this.state.result
在获取后复制一些数据(而不是复制countries
参考)分页 - '结果'(不适合上述)记录未根据范围进行子选择
currentPage
使用反应开发工具检查浏览器中的状态变化(检查是否正常工作)。
推荐阅读
- python - python中next()函数的时间复杂度是多少?
- python - 无法在 Python 中打开 HDF5 文件
- linux - 如何使用合并命令将此文本文件中的 5 行与另一个文本文件中的 1 行合并?
- php - 可以通过CSS将列表从垂直更改为水平吗?
- css - 我使用自定义 css 在 wordpress 标题上制作了一个按钮,但我无法更改按钮上文本的颜色?
- discord.js - 如何创建播放音频文件并将其广播到服务器中的特定频道的命令
- gentics-mesh - 如何在 Gentics Mesh 中播种模式
- r - ggplot2 突出显示字母串
- c++ - C++ 代码适用于某些输入,但不适用于其他输入
- javascript - 如果数字是偶数,如何舍入,如果是奇数,如何舍入?