javascript - 建议在索引更改时如何更新数组
问题描述
我想更新数组元素,我正在使用索引来引用位置。问题是在搜索名称(关键字)时索引发生变化,它基本上将名称设置为用户数组中的错误元素(因为从过滤后的用户数组中获取索引)
const [users, setUsers] = useState(["John", "Marty", "Mary", "Johanna"]);
const [keyword, setKeyword] = useState("")
const updateName = (index, name) => {
const newState = [...users];
newState[index] = name;
setNames(newState);
};
我有一个输入字段来搜索名称
<input value={keyword} onChange={(e) => setKeyword(e.target.value)} placeholder="search"/>
然后我用每个名称渲染一个子组件,并传递一个道具来更新名称
users
.filter((user) =>
user.toLowerCase().includes(keyword.toLowerCase())
)
.map((user, index) => (
<User
user={user}
updateName={updateName}
index={index}
key={index}
/>
))
我的用户组件
const User (props) => <button onClick={props.updateName(index, "some name")}>{props.user}</button>
这工作得很好。除非关键字更改。因为 users.map 会改变并且显然会改变索引。但问题是我正在使用索引来更新数组元素。
例如,如果我搜索“Ma”关键字。2 个名称匹配,因此过滤用户的索引将更改为 0、1,但用户数组仍然相同。
我怎么解决这个问题?谢谢你。
解决方案
如果您想保留当前的数据结构,您可以通过仅有条件地渲染组件来放弃filter
并在您的函数中进行过滤。这样,您就不会丢失索引的核算。map
User
users
.map((user, index) => (
user.toLowerCase().includes(keyword.toLowerCase()) && <User
user={user}
updateName={updateName}
index={index}
key={index}
/>
))
推荐阅读
- python - 同一com端口上python中串行对象的多个实例
- linux - 让进程在后台挂起/运行并写入同一个文件
- google-sheets - 谷歌表格 - 根据字符串输入在公式中包含表格名称
- c++ - 使用向量时的无符号整数或迭代器?
- postgresql - JOOQ 时间戳字段默认值与数据库默认值不同
- android - 在 androids Talkback 可访问性中将缩写或首字母发音为单个字符
- java - 我将如何写入缓冲区并在 Java 画布中绘制它?
- python - 我如何按三列分组并计数并将结果传输到一个数据框中
- qt - 在特定时间执行函数 QT
- jquery - 仅在 IE11 上出现 Jquery 错误 - Foreach(anchor) 语法错误