使用 onChange 在 Rect 上获取输入文本值会在键入时错过第一个字母,在删除时也会错过

Getting input text values on Rect using onChange misses first letter when typing and when deleting it misses too

我有一个小文本字段来过滤我的 React 应用程序上的对象数组,但是当我键入 onChange 事件时会跳过第一个字符,因此它没有正确过滤数组然后当我删除文本时它不会删除第一个我写的信要删除过滤器,您必须重新加载页面。

这是我的应用程序:

    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;

这是包含输入的导航组件:

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 函数上得到的值时,第一个字母总是白色 space 因此,当您擦除过滤器时,结果不会设置为完整数组。

这里有几个问题。

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));