reactjs - 在 React.js 中使用分页进行实时搜索
问题描述
我想在所有页面中搜索,但我的代码只在当前页面中搜索。
例如,当我在页面 2/5 中输入出现在此页面中的游客的姓名时,它会向我显示数据,
但是当我在页面 4/5 中输入游客时,它不会显示任何内容.
我在后端使用 Laravel。
这是后端代码:
$tourists = Tourist::where('hotel_id', $request->hotel_id)->orderBy('created_at', 'DESC')->paginate(10);
return $toursits;
前端代码:
this.state = {
activePage: 1,
tourists: []
}
async componentDidMount() {
await this.getTourists();
}
async getTourists() {
let response = await callApi('tourists/paginate', { page: this.state.activePage, hotel_id: this.context.hotel_id[0] });
this.setState({ tourists: response.data, perPage: response.meta.per_page, total: response.meta.total, lastPage: response.meta.last_page });
}
渲染方法:
{this.state.tourists
.filter(x => new RegExp (this.state.first_name, 'i').test(x.first_name)
.map((tourist, i) =>
<tr>
<td>{tourist.first_name}</td>
</tr>)}
解决方案
您正在从后端获得分页的结果列表,但您正在前端实现搜索功能。
当您第一次访问您的页面时,您会从服务器获得前 10 个结果。当时,您的 React 应用程序不知道还有更多结果需要解析,并且只能“看到”您从服务器发送的 10 个分页结果。通过过滤这些结果,您将无法获得最初不是由服务器发送的任何其他结果。
您有 2 个解决方案:
- 实现分页客户端,
- 在服务器端实现搜索功能
鉴于您已经在服务器上实现了分页,我假设您有很多结果,并且一次发送所有结果是不切实际的。
这给我们留下了选项 n°2。添加到您的代码示例中,您可以执行以下操作:
$tourists = Tourist::where('hotel_id', $request->hotel_id)
// Add this to filter results by first_name
->where('first_name', 'like', "%{$request->first_name}%"))
->orderBy('created_at', 'DESC')->paginate(10);
return $tourists;
推荐阅读
- javascript - 如何在断点处重定向到另一个页面?
- mongodb - Mongoexport 给出身份验证失败错误
- batch-file - 任务计划程序,运行 .bat 不启动 java 应用程序
- java - 不允许访问以检索脚本
- python - 为什么networkx有这么多随机图生成器?
- database - Hasura:如何过滤和然后排序,具有一对多关系
- git - 从另一个远程分支拉出“已经是最新的”消息
- c# - C# 问题 - 将日期时间转换为货币
- encoding - Rust如何对带有字节参数的字符串进行urlencode?
- python - SimilarityTransform(scikit-image)和warpAffine(openCV)之间的区别?