如何使用特定索引,React State更新数组中的对象元素

问题描述

下面的代码是我要在状态下更新main_id和sub_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:[]
      }
   ]
}

解决方法

好像您正在尝试在状态更新程序功能(setState)和当前状态对象(state)之间进行传播。

浅拷贝现有状态,然后在索引匹配时也浅拷贝该元素。您还应该使用功能状态更新。

const handleState = index => v => {
  setState(state => ({
    ...state,// <-- copy previous state
    ids: state.ids.map((x,i) =>
      i === index
        ? {
            ...x,// <-- on match,copy element,then update properties
            main_id: v.id,sub_ids: [],}
        : x,// <-- non-match,just pass element through
    ),}));
};

虽然状态看起来会覆盖整个元素对象,但是简化状态可能会更清晰一些。

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

const handleState = index => v => {
  setIds(ids => ids.map((x,i) =>
      i === index
        ? {
            main_id: v.id,),}));
};

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...