【发布时间】:2020-07-14 12:24:17
【问题描述】:
我有父组件和多个子组件。每个子组件负责获取数据并绑定到本地存在的对象。
现在在父组件中,我有保存方法。当触发保存点击事件时,我需要从孩子收集所有对象并映射到单个对象并传递给 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);
});
}
【问题讨论】:
-
您是否需要在按保存时收集数据,或者在每个子组件上都有一个 onChange 回调更有意义?如果每个组件都有一个 onChange 回调,那么父组件可以在提交之前构建对象以保存,而不是在提交时保存。
-
@NickHoward 这是我的最后一个选择,但是当我点击保存时,我试图仅检索子对象
标签: reactjs redux react-redux react-hooks