反应-onChange函数中的更新状态(useState)问题

时间:2020-04-29 21:28:40

标签: reactjs use-state

我在更新表单的handleItemChange函数上的状态时遇到问题。你有解决方案吗 ?非常感谢你...

const [items, setItems] = useState([]);

const addPrestation = () => {

    const id = Date.now().toString();
    const prestation = {...items};
    prestation[id] = {
        customer:customer,
        id: id,
        delivery: "",
        quantity: "",
        unit: "",
        unitPrice: "",
        tva: "",
        htAmount: "",
        ttcAmount: ""
    }
    setItems([...items, {prestation:prestation}])
}

 const handleItemChange = (event, prestation, field ) => {
   const value = event.target.value;
   const clonePresta = {...prestation};
   clonePresta[field] = value;
   const clonePrestations = {...items};
   clonePrestations[clonePresta.id] = clonePresta;

   setItems(???)
}

2 个答案:

答案 0 :(得分:0)

我认为您应该这样做:

const handleItemChange = (event, prestation, field ) => {
   const value = event.target.value;
   const clonePresta = {...prestation};
   clonePresta[field] = value;
   const clonePrestations = {...items};
   clonePrestations[clonePresta.id] = clonePresta;

   setItems([...items, {presentation: clonePresta})
}

答案 1 :(得分:0)

const handlePrestaChange = ({currentTarget}) => {
    const {name, value, id} = currentTarget;
    const clonePresta = {...prestation}
    clonePresta[name] = value;
    setPrestation({...prestation, [name]: value })
    const tabItems = [...items];
    tabItems[id] = clonePresta;
    setItems([...tabItems])
}
相关问题