有条件地更新父类传递的事件处理程序中的子组件的状态


const Child = (props) => {
const [val, setVal] = useState(props.val);
const handleCreate = (newData) => new Promise((resolve, reject) => {
setTimeout(() => {
{
const transactions = JSON.parse(JSON.stringify(tableData));
const clean_transaction = getCleanTransaction(newData);
const db_transaction = convertToDbInterface(clean_transaction);
transactions.push(clean_transaction);
// The below code makes post-request to 2 APIs synchronously and conditionally updates the child-state if calls are successful.
**categoryPostRequest(clean_transaction)
.then(category_res => {
console.log('cat-add-res:', category_res);
transactionPostRequest(clean_transaction)
.then(transaction_res => {
addToast('Added successfully', { appearance: 'success'});
**setVal(transactions)**
}).catch(tr_err => {
addToast(tr_err.message, {appearance: 'error'});
})
}).catch(category_err => {
console.log(category_err);
addToast(category_err.message, {appearance: 'error'})
});**
}
resolve()
}, 1000)
});
return (
<MaterialTable
title={props.title}
data={val}
editable={{
onRowAdd: handleCreate
}}
/>
);
}
const Parent = (props) => {
// some other stuff to generate val
return (
<Child val={val}/>
);
}

我正在努力实现这一点:我想将handleCreate(粗体部分(中函数的请求后部分移到Child类可以调用的Parent组件上。其思想是使组件抽象化,并可由其他类似的父类重用。

在父级中创建函数,并将其传递给props:中的子级

const Parent = (props) => {
// The handler
const onCreate = /*...*/;
// some other stuff
return (
<Child ...props onCreate={onCreate}/>
);
}

然后让孩子用它需要的任何参数调用函数(在你的例子中似乎没有任何参数,例如,你没有在其中使用val(:

return (
<MaterialTable
title={props.title}
data={val}
editable={{
onRowAdd: props.onCreate // Or `onRowAdd: () => props.onCreate(parameters, go, here)`
}}
/>
);

旁注:没有理由将props.val复制到子组件内的val状态成员,只需使用props.val即可。

旁注2:摧毁道具通常很方便:

const Child = ({val, onCreate}) => {
// ...
};

旁注3:您的Parent组件通过...props:调用Child及其所有道具

return (
<Child ...props onCreate={onCreate}/>
);

这通常不是最好的。只传递Child它实际需要的内容,在这种情况下,传递valonCreate:

return (
<Child val={props.val} onCreate={onCreate}/>
);

最新更新