我有一个小的文本字段来过滤我的React应用程序上的对象数组,但是当我键入onChange事件跳过第一个字符,所以它不能正确过滤数组,然后当我删除文本时,它不会删除我写的第一个字母,所以要删除过滤器,你必须重新加载页面。
这是我的app:
function App() {
const [memes, setMemes] = useState([]);
const [filteredMemes, setFilteredMemes] = useState([]);
// const [filter, setFilter] = useState("");
useEffect(() => {
(async function getData() {
await getMemes();
})();
}, []);
const getMemes = async () => {
const results = await memeService.getMemes();
setMemes(results.data.data.memes);
setFilteredMemes(memes);
}
const handleSearch = (event) => {
const filter = event.target.value;
setFilteredMemes(memes);
filteredMemes.filter((meme) => meme.name.toUpperCase().search(filter.toUpperCase()) >= 0);
}
return (
<>
<Nav handleSearch={handleSearch} />
<Router>
<Switch>
<Route path="/:id/edit" children={<Editor />} />
<Route path="/:id/new" children={<New />} />
<Route path="/">
<div className='container'>
{filteredMemes.map(meme => <Meme key={meme.id} meme={meme} />)}
</div>
</Route>
</Switch>
</Router>
</>
)
}
export default App;
这是包含输入的Nav组件:
import './Nav.css';
const Nav = ({handleSearch}) => {
return (
<div className='nav'>
<input type='text' placeholder='Search' onChange={handleSearch} />
<a href='/'>Home</a>
</div>
)
}
export default Nav;
当我在控制台上检查我在handleSearch
函数上获得的值时,总是将第一个字母作为空白,因此当您擦除过滤器时,结果不会设置为完整数组。
这里有几个问题。
setMemes(results.data.data.memes); //you request React to update memes at some point in the future
setFilteredMemes(memes); // you set filteredMemes to memes, which is still [] at this point
setFilteredMemes(memes); // you request to change filteredMemes to the unfiltered version (again at some later point)
filteredMemes.filter((meme) => meme.name.toUpperCase().search(filter.toUpperCase()) >= 0); //filter creates a new array, not assigned to anything
应该
setMemes(results.data.data.memes);
setFilteredMemes(results.data.data.memes);
setFilteredMemes(memes.filter((meme) => meme.name.toUpperCase().search(filter.toUpperCase()) >= 0));