首页 > 解决方案 > 建议在索引更改时如何更新数组

问题描述

我想更新数组元素,我正在使用索引来引用位置。问题是在搜索名称(关键字)时索引发生变化,它基本上将名称设置为用户数组中的错误元素(因为从过滤后的用户数组中获取索引)

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,但用户数组仍然相同。

我怎么解决这个问题?谢谢你。

标签: javascriptreactjs

解决方案


如果您想保留当前的数据结构,您可以通过仅有条件地渲染组件来放弃filter并在您的函数中进行过滤。这样,您就不会丢失索引的核算。mapUser

users
  .map((user, index) => (
    user.toLowerCase().includes(keyword.toLowerCase()) && <User
      user={user}
      updateName={updateName}
      index={index}
      key={index}
    />
  ))

推荐阅读