开发者问题收集

反应问题 - 无法分配给对象'[object Array]'的只读属性'0'---

2022-11-10
972

是什么导致了 ff 问题?无法分配给对象 '[object Array]' 的只读属性 '0'?

任何想法都会受到赞赏。谢谢。

#ts 代码片段

 const [RegionalList, setRegionalList] = useState<IRegionalList[]>(RegionalListData);


 const setEmailValue = (event: any, regionalId: number, index: number) => {
    setRegionalList((prevState: IRegionalList[]) => {
      const newState = prevState.map((prop: IRegionalList) => {
        if (prop.id === regionalId) {
          prop.emails[index] = { emailAddress: event.target.value, id: null };
          return { ...prop };
        }
        return prop;
      });
      return newState;
    });
  }
1个回答

这是我建议的方法:

 const [RegionalList, setRegionalList] = useState<IRegionalList[]>(RegionalListData);


 const setEmailValue = (event: any, regionalId: number, index: number) => {
    setRegionalList((prevState: IRegionalList[]) => {
      const newState = prevState.map((prop: IRegionalList) => {
        if (prop.id === regionalId) {
         return { ...prop,emails:[...prop.emails.filter( (_,i)=>i !== index ),{ emailAddress: event.target.value, id: null }] } 
        }
        return prop;
      });
      return newState;
    });
  }

如果您关心列表的顺序,可以这样做:

    const setEmailValue = (event: any, regionalId: number, index: number) => {
    setRegionalList((prevState: IRegionalList[]) => {
      const newState = prevState.map((prop: IRegionalList) => {
        if (prop.id === regionalId) {
         let emails = prop.emails;
         emails[index] = { emailAddress: event.target.value, id: null };
          return { ...prop,emails }
        }
        return prop;
      });
      return newState;
    });
  }

如果它解决了您的问题,请告诉我

Ali Sattarzadeh
2022-11-10