简体   繁体   English

通过对象数组的 onchange 设置状态

[英]setState through onchange of an array of object

how can I update my values of an array and add values after every form submission, all things working fine except for the onchange function, or if anybody has any better way to do it do let me know.如何在每次提交表单后更新我的数组值并添加值,除了 onchange 函数之外所有的东西都工作正常,或者如果有人有更好的方法让我知道。

an array of objects:对象数组:

 const [detailPetition, setDetailPetition] = useState([{
    description: "",
    recipientAddress: "",
    amountNeed: "",
    grandPermissionCount: 0,
    isFullfilled: false,
  }]);

Onchange function: Onchange函数:

const enterDetails = (event,id) => {
    const { value, name } = event.target;
    setDetailPetition((pervState) =>{
      return pervState.map((data,index)=>{
          if(index===id)
          return {...data,[name]:value};
          else
          return data;
      })
      })
    };

mapping data映射数据

 const Mappetition = () => {
    const petitiondetail = detailPetition.map((data, index) =>
      <Petition
        key={index}
        account={account}
        description={detailPetition.description}
        recipientAddress={detailPetition.recipientAddress}
        amountNeed={detailPetition.amountNeed}
        enterdetail={enterDetails}
        submitpetition={enterPetition}
      />
    )
    return petitiondetail;
  }

There is only 1 object.只有 1 个对象。 So no need for an array here所以这里不需要数组

   const [detailPetition, setDetailPetition] = useState({
    description: "",
    recipientAddress: "",
    amountNeed: "",
    grandPermissionCount: 0,
    isFullfilled: false,
  });

onChange,改变,

        const enterDetails = (event) => {
         const { value, name } = event.target;
         setDetailPetition({...detailPetition, [name]: value);

Data rendering,数据渲染,

return (
  <Petition
    key={index}
    account={account}
    description={detailPetition.description}
    recipientAddress={detailPetition.recipientAddress}
    amountNeed={detailPetition.amountNeed}
    enterdetail={enterDetails}
    submitpetition={enterPetition}
  />
     )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM