【问题标题】:How to update object element in array in React State如何在 React State 中更新数组中的对象元素
【发布时间】:2020-08-12 01:37:48
【问题描述】:

下面的代码是我正在尝试更新main_idsub_ids 的状态。

我被困在这里...

const [state, setState] = useState({
  ids: [
    {
      main_id: null,
      sub_ids: []
    }
  ]
});

// this is what I've tried..
const handleState = index => (v) => {
  setState({ ...setState, ids: setState.ids.map((x,i) => (
    i === index ? {x.main_id: v.id, sub_ids: []})
  ))})
}

我在同一个组件上使用这个函数,这意味着它添加了具有不同对象的数组的特定索引。

<componentOne onChange ={handleState(k)} />
<componentTwo onChange={handlestate(k)} />
state = {
  ids:[
    {
     main_id: v.id,
     sub_ids:[]
    },
    {
     main_id: v.id,
     sub_ids:[]
    }
  ]
}

【问题讨论】:

  • 请将您的整个组件显示为minimal reproducible example。请注意onChange 将使用event 调用处理程序,而不是index
  • 我正在使用 array.map 函数循环相同的组件并为其分配索引

标签: reactjs redux react-redux react-hooks


【解决方案1】:

请参考以下代码:

const [state, setState] = useState({
  ids: [
    {
      main_id: null,
      sub_ids: []
    }
  ]
});

// this is what I've tried..
const handleState = index => (v) => {
  setState({ ...state, ids: state.ids.map((x, i) => (
    i === index ? { main_id: v.id, sub_ids: [] } : x
  ))})
}

【讨论】:

    猜你喜欢
    • 2021-09-06
    • 2021-11-07
    • 2020-11-07
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    相关资源
    最近更新 更多