reactjs - 处于反应状态的数组未正确更新
问题描述
我基本上尝试将所有位置数组中的过滤项目更新为 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;
解决方案
推荐阅读
- apache - 为什么不能在 jUDDI 中传递 Gui 用户
- python - 给定要裁剪的四个角的坐标,如何裁剪图像
- java - MongoDB Morphia 仅使用自定义解码转换器和默认编码转换器
- c++ - 关于模板和类型名的问题
- vsto - 如何安装 VSTO Outlook 插件?
- angular - 当 ChildComponent 发生变化时如何监听然后在 ParentComponent 中执行方法?
- c# - 如何从代码中获取 NavigationWindow 指向的 WPF 页面
- python - Tensorflow:如果灰度将图像转换为rgb
- ios - 如何在开发中测试 Apple Universal Links?
- python - 如何更改 Plotly 保存图像的步骤?