首页 > 解决方案 > 在 UI 中重复 React 组件

问题描述

我正在使用 React.js(没有 Redux 或其他状态管理库)

我有一个带有两个屏幕的单页应用程序:“MainL 列表”和“我的列表”当用户从“主列表”中选择一个项目时,该项目将被添加到“我的列表”中。

我遇到的问题是,当用户从主列表中选择一两个项目然后切换到“我的列表”时,他有时会看到相同的项目被复制了两次。

错误使用密钥 ID 的数组突变似乎是一个问题。两个屏幕中的项目都由一个数组表示。所以主列表的一个数组和我的列表的一个数组

要切换屏幕的可见性,我使用以下代码:

this.state.screenLocation === "MainList" ? (
  this.state.cardsMainList.map((value, index) => (
    <ItemCard key={index} card={value} location={"MainList"} />
  ))
) : this.state.screenLocation === "MyList" ? (
  this.state.cardsMyList.map((value, index) => (
    <ItemCard
      key={index + 100000}
      card={value}
      location={"MyList"}
      added={true}
    />
  ))
) : (
  <div> Error: Wrong Screen Location </div>
);

当我切换到我的列表屏幕时,我从数据库中获取项目信息,然后更改我的列表的数组:

let cards = [];

//then an API call to the server to retrieve items from the DB
// ........
//then the following:

cards = response.data.results[0];

this.setState({ cardsMyList: cards });

我是否错误地改变了数组?我是否使用

先感谢您。

标签: javascriptreactjs

解决方案


推荐阅读