我有父级组件和多个子级组件。每个子组件负责获取数据并绑定到本地存在的对象。
现在在父组件中,我有保存方法。触发保存点击事件时,我需要从子级收集所有对象并将其映射到单个对象并传递给api。有人可以帮我怎么做吗?
下面给出了一些我尝试过但无法成功的方法。我在这里用过useRef。
// One of the child component
const Questionnaire = forwardRef((props,ref) => {
useImperativeHandle(ref, () => ({
getUserEnteredObjectRef() {
return userEnteredData;
}
}));
});
//in my parent
function HandleSaveRequest() {
console.log('Save Request Command:');
let qtnObj = questionnaireRef.current.getUserEnteredObjectRef(); // prints the object
console.log(qtnObj); // displays the object from the child
setSaveRequestObj({qtn:qtnObj}); // don't get assigned and the object will be empty. strange is when i click the save 2nd time i get the object assigned.
axios.post(API, SaveRequestObj).then(res => {
goToDashboard();
}).catch(err => {
console.log('Error while saving' + err.message);
});
}
答案 0 :(得分:0)
请参见refs doc:
您需要使用current
来访问getUserEnteredObjectRef
let qtnObj = questionnaireRef.current.getUserEnteredObjectRef();