首页 > 解决方案 > 处于反应状态的数组未正确更新

问题描述

我基本上尝试将所有位置数组中的过滤项目更新为 dropDownLocation 数组,但它没有正确更新。在输入字段的第一次更改时,它会错误地更新数组,而第二次更改它不会更新它。

它向我显示了这个输出,但我不知道为什么会这样

 import logo from "./logo.svg";
        import "./App.css";
        import { useState, useEffect } from "react";
        
    function App() {
      // location entered by the user
      const [location, setlocation] = useState("");
    
      const [allLocations, setallLocations] = useState(["F-1", "F-2", "G-1", "G-2"]);
    
      const [dropDownLocations, setdropDownLocations] = useState([]);
    
      const filterLocations = (userInput) => {
        console.log("user input ", location);
    
        allLocations.map((i) => {
          if (i.includes(location)) {
            console.log("true at ", i);
            setdropDownLocations([...dropDownLocations, i]);
          } else {
            setdropDownLocations([]);
          }
        });
    
        console.log("after map ", dropDownLocations);
      };
    
      return (
        <div className="App">
          <div>
            <input
              value={location}
              onChange={(e) => {
                setlocation(e.target.value);
                filterLocations(e.target.value);
              }}
            />
            <ul>
              {dropDownLocations.map((i) => (
                <li key={i}>{i}</li>
              ))}
            </ul>
          </div>
        </div>
      );
    }
    
    export default App;

标签: reactjs

解决方案


你不需要那么复杂,只需根据用户的输入过滤数组

const filterLocations = (userInput) => {
  setdropDownLocations(
    allLocations.filter((location) => location.includes(userInput))
  );
};

我在这个工作示例中为您简化了:

编辑空架构-l0q8l


推荐阅读