React过滤器功能



我是新手,正在学习React。我想做一个搜索过滤器,我跟着youtube做了一个功能。但是它不能处理错误"Array.prototype.filter()期望在箭头函数array-callback-return"结束时返回一个值。我什么都做了。它仍然不起作用。谁来帮帮我。

const boards = this.state.boards.filter((board)=>{
if(this.state.search == null)
return board
else if(board.title.toLowerCase().includes(this.state.search.toLowerCase()) || board.content.toLowerCase().includes(this.state.search.toLowerCase())){
return board
}
}).map(board=>{
return(
<tr key = {board.idx}>
<td> {board.idx} </td>
<td><button  className="btn btn-link" onClick = {() => this.BoardDetail(board.idx)}> {board.title}</button></td>
<td> {board.insertTime} </td>
<td> {board.updateTime} </td>
<td> {board.viewCnt} </td>
</tr>
)
})

在这里做一些假设,因为正如用户Mohit Kushwaha所说,初始状态对于正确调试是必要的。

你的过滤器函数返回错误的"类型"的价值。如果你看array。prototype。过滤器,您将注意到回调请求一个函数,该函数将返回truefalse值。

callbackFn

函数是谓词,用于测试中的每个元素数组中。返回一个强制true的值以保持元素,否则返回false

这意味着在您的过滤器函数中,您应该返回true/false,而不是返回board。在下面的示例中,当我认为您试图在数组中保留某些东西时,我将返回true-例如,当this.state.search与您的董事会的标题或内容相匹配时,当您想要删除它时,false,例如,如果没有匹配(再次做出假设-您应该真正尝试用尽可能多的相关细节来制定您的问题):

const boards = this.state.boards.filter((board) => {
if(this.state.search == null) {
// If there is no search value, don't filter anything
return true 
} else if (
board.title.toLowerCase()
.includes(this.state.search.toLowerCase()) || 
board.content.toLowerCase()
.includes(this.state.search.toLowerCase())
) {
// If the search string matches, keep the `board` 
return true 
} else {
// If there is a search string and it does not match, filter out the `board` 
return false 
}
})
.map(/* ...the rest of your map function */)

你的问题是在filter功能:不是所有的路径返回的东西(我的意思是,在内部if你忘记添加最后的else的情况下)。

但是你可以让事情变得更简单。事实上,考虑到filter函数需要一个布尔条件(用于过滤this.state.boards元素),您可以这样写:

const boards = this.state.boards.filter((board)=>{
return this.state.search === null || (board.title.toLowerCase().includes(this.state.search.toLowerCase()) || board.content.toLowerCase().includes(this.state.search.toLowerCase()))
}).map(board=>{
return(
<tr key = {board.idx}>
<td> {board.idx} </td>
<td><button  className="btn btn-link" onClick = {() => this.BoardDetail(board.idx)}> {board.title}</button></td>
<td> {board.insertTime} </td>
<td> {board.updateTime} </td>
<td> {board.viewCnt} </td>
</tr>
)
})

只要把你的条件放在or里,错误就会消失。

您可以尝试使用reduce代替filter,这将有点容易,如下所示:

const boards = this.state.boards.reduce((acc,board) => {
if(this.state.search == null)
return acc.concat(board);
else if(board.title.toLowerCase().includes(this.state.search.toLowerCase()) || board.content.toLowerCase().includes(this.state.search.toLowerCase())){
return acc.concat(board);
}
//else return acc
return acc;
},[])
.map(/* ...the rest of your map function */)

最新更新