我正在尝试使用挂钩从不同的子组件中收集并创建对象。
有多个子组件,这些子组件将更新父组件中的状态并创建一个主对象以将其发送到API。
// creating a hook
const [formData, setFormData] = useState({});
// Getting data from the child and setting it using a hook set method
const deliveryContactDetails = deliveryData => {
contacts.push(deliveryData);
};
const productNameData = productData => {
setFormData(...formData, productData);
}
const onboardDetailsData = detailsData => {
setFormData(...formData, detailsData)
}
// Using ref to call the child and send data to parent
useImperativeHandle(ref,() => ({
sendData() {
productRef.current.sendData()
detailsRef.current.sendData()
deliveryRef.current.map(
ref => ref.current.sendData()
);
setFormData(...formData, { contacts: contactArray });
props.saveItem(tempObj);
}
}));
在控制台中获取错误
corporateOnboardingDetails.js:137未被捕获的TypeError:在Object.productNameData [作为saveProduct](corporateOnboardingDetails.js:137)上不能迭代formData
答案 0 :(得分:0)
您试图将对象作为参数传入函数调用。您需要将对象传递给setFormData
函数(您忘记了括号{}
)。
const productNameData = productData => {
setFormData({...formData, productData});
}
const onboardDetailsData = detailsData => {
setFormData({...formData, detailsData});
}