【问题标题】:Change List of objects in position using map for Reactjs [duplicate]使用 Reactjs 的地图更改位置对象列表 [重复]
【发布时间】:2021-03-26 11:35:00
【问题描述】:

我想知道如何将“检查”项从我的数组列表的第 5 位更改为真。

const optionsConsultation = [
  { label: "Maçã", check: false, id: 0, disable: false },
  { label: "Banana", check: false, id: 1, disable: false },
  { label: "Pera", check: false, id: 2, disable: false },
  { label: "Uva", check: false, id: 3, disable: false },
  { label: "Morango", check: false, id: 5, disable: false},
  { label: "Laranja", check: false, id: 6, disable: false }
];

export default () => {
  const [datas, setDatas] = useState(optionsConsultation);

  useEffect(() =>{
    const resetData = datas.map(checks => checks)
    )

【问题讨论】:

  • 这能回答你的问题吗? - stackoverflow.com/questions/54676966/…
  • 你想让check: true 用于resetData 中带有id: 5 的项目吗?
  • 下午好,威廉,你不会去的,因为我想更改作为 spreed 运算符传递的对象的信息。例如{... item, [position5]: true}
  • 我想带上整个数组,就在数组5的位置把check key改为true

标签: javascript reactjs


【解决方案1】:

如果您只想为带有id: 5 的项目创建一个带有check: true 的新resetData 数组。

const resetData = optionsConsultation.map((item) => {
  if (item.id === 5) {
    return { ...item, check: true }
  }
  
  return item;
});

如果你只想依赖索引

const resetData = optionsConsultation.map((item, index) => {
  if (index === 4) {
    return { ...item, check: true }
  }
  
  return item;
});

【讨论】:

  • 我更喜欢你的,因为它给了我更多的选择来改变其他东西,你在对象上喷了,我没有注意到的东西,谢谢
  • { ...item, check: true } 就够了,没必要为了马上传播而创建新对象。
  • 是的,我用@EmileBergeron 的建议修改了解决方案
  • 你就是男人!
【解决方案2】:

更改嵌套对象/数组中的值可能非常乏味。

如果在您的应用程序中经常这样做,我建议您尝试使用 Immer (https://github.com/immerjs/use-immer)。

要不然这样就很好了:

//
const targetItemIndex = 5;
const resetData = [
  ...datas.slice(0, targetItemIndex),
  { ...datas[targetItemIndex], check: true },
  ...datas.slice(targetItemIndex + 1)
];
//

或者像这样:

const targetItemIndex = 5;
const resetData = datas.map((item, index) => {
  if (index === targetItemIndex) {
    return { ...item, check: true };
  }

  return item;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-06
    • 2020-06-08
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    相关资源
    最近更新 更多