过滤器功能不起作用并给出错误
Posted
技术标签:
【中文标题】过滤器功能不起作用并给出错误【英文标题】:filter function is not working and giving errors 【发布时间】:2022-01-17 11:59:31 【问题描述】:我正在尝试使用搜索过滤器来搜索表的所有元素,但我收到此错误记录。过滤器不是一个函数,如果将其删除,我将收到此错误 record.map 不是函数。所以我不明白这个问题我找不到解决方案
import useEffect, useState from "react";
import axios from "axios";
import React from 'react';
function Read()
const [record, setRecord] = useState('');
const [searchTerm, setSearchTerm] = useState('');
useEffect(() =>
axios.get('https://jsonplaceholder.typicode.com/comments')
.then((response) =>
console.log(response.data);
setRecord(response.data);
)
, [])
return (
<>
<input type="text" onChange=(e) => setSearchTerm(e.target.value) placeholder="Search" />
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Role</th>
</tr>
</thead>
<tbody>
record
.filter((val) =>
if (searchTerm === "")
return val;
else if (
val.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
val.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
val.body.toLowerCase().includes(searchTerm.toLowerCase())
)
return val;
return false;
)
.map((demo, i)=>
return(
<tr key=i>
<td>demo.name</td>
<td>demo.email</td>
<td>demo.body</td>
</tr>
)
)
</tbody>
</table>
</>
);
export default Read;
【问题讨论】:
response.data
一定不能返回数组,你能粘贴响应的样子吗
【参考方案1】:
我认为由于渲染问题,有时记录只是空值。
您只需在返回上方添加if (!record) return <></>
此代码即可。
而且你最好将你的记录初始值修改为[]
而不是''
import useEffect, useState from "react";
import axios from "axios";
import React from 'react';
function Read()
const [record, setRecord] = useState([]); // ??♀️??♀️??♀️??♀️??♀️??♀️??♀️??♀️??♀️ HERE!!
const [searchTerm, setSearchTerm] = useState('');
useEffect(() =>
axios.get('https://jsonplaceholder.typicode.com/comments')
.then((response) =>
console.log(response.data);
setRecord(response.data);
)
, [])
if (!record) return <></> // ??♀️??♀️??♀️??♀️??♀️??♀️??♀️??♀️??♀️??♀️??♀️??♀️??♀️??♀️??♀️??♀️??♀️ HERE!!
return (
<>
<input type="text" onChange=(e) => setSearchTerm(e.target.value) placeholder="Search" />
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Role</th>
</tr>
</thead>
<tbody>
record
.filter((val) =>
if (searchTerm === "")
return val;
else if (
val.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
val.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
val.body.toLowerCase().includes(searchTerm.toLowerCase())
)
return val;
return false;
)
.map((demo, i)=>
return(
<tr key=i>
<td>demo.name</td>
<td>demo.email</td>
<td>demo.body</td>
</tr>
)
)
</tbody>
</table>
</>
);
export default Read;
【讨论】:
以上是关于过滤器功能不起作用并给出错误的主要内容,如果未能解决你的问题,请参考以下文章