我正在学习Reaction,特别是试图通过搜索过滤数据.到现在为止还好.
当我试图从输入中清除结果时,我得到的是搜索的数据,而我想要的是所有的初始数据.
我怎么才能解决这个问题呢?
import { FC, useEffect, useState } from 'react';
import './style.css';
export const App: FC<{ name: string }> = ({ name }) => {
const [users, setUsers] = useState([]);
const [searched, setSearched] = useState('');
useEffect(() => {
async function getUsers() {
let response = await fetch(
'https://jsonplaceholder.typicode.com/users'
).then((response) => response.json());
setUsers(response);
}
getUsers();
}, []);
useEffect(() => {
if (searched.length >= 2) {
async function getUsers() {
let response = await fetch(
'https://jsonplaceholder.typicode.com/users'
).then((response) => response.json());
setUsers(
response.filter((resp) =>
resp.name.toLowerCase().includes(searched.toLowerCase())
)
);
}
getUsers();
}
}, [searched]);
return (
<>
<input
type="text"
placeholder="Enter name"
value={searched}
onChange={(ev) => setSearched(ev.target.value)}
/>
{users && users.map((user) => <p>{user.name}</p>)}
</>
);
};