如何通过关键词模糊搜索帖子,解决includes判断逻辑不生效问题
模糊搜索功能修改方案
问题根因
你原有逻辑的包含关系写反了:
- 错误写法
query.includes(post.title)是判断「用户输入的搜索词里是否包含完整的帖子标题」,完全不符合模糊搜索的预期 - 正确逻辑应该是判断「帖子标题是否包含用户输入的搜索关键词」,即
post.title.includes(query)
另外建议增加大小写不敏感匹配,避免用户输入大小写和标题不一致时匹配失败,同时调整判断顺序,query为空时直接返回全部帖子。
修改后代码
{(() => { if (isLoading) return <LoadingBlock /> if (!isLoading && postList.length === 0) return <NoDataWarning text='Nenhuma postagem encontrada.' /> return postList.map((post, index) => { // 搜索逻辑调整 if (query) { // 统一转小写实现大小写不敏感匹配,不需要可以去掉toLowerCase() const lowerQuery = query.trim().toLowerCase() const lowerTitle = post.title.trim().toLowerCase() if (!lowerTitle.includes(lowerQuery)) { return null } } return ( <PostContainer position={index}> <PostBanner /> <PostInfoContainer> <span> <AiFillCalendar /> {new Date(post.createdAt).toLocaleDateString()} </span> <span> <FaUserCircle /> {`${post.firstName} ${post.lastName}`} </span> </PostInfoContainer> <PostTitle>{post.title}</PostTitle> </PostContainer> ) }) })()}
可选优化
如果需要支持多关键词匹配,可以把用户输入的query按空格拆分后逐个判断是否在标题中存在,示例逻辑:
if (query) { const lowerQueryArr = query.trim().toLowerCase().split(/\s+/) const lowerTitle = post.title.trim().toLowerCase() // 只要有一个关键词匹配就返回 const isMatch = lowerQueryArr.some(keyword => lowerTitle.includes(keyword)) if (!isMatch) return null }
内容的提问来源于stack exchange,提问作者Lucas Abrantes
相关产品推荐
相关产品推荐

