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组件上。想法是使Component抽象并可由其他类似的Parent-class重用。
在父级中创建函数,然后在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
子组件内的state成员props.val
。
旁注2:使用道具通常可以方便地进行破坏:
const Child = ({val, onCreate}) => {
// ...
};
旁注3:您的Parent
组件Child
可以通过以下方式调用其所有道具...props
:
return (
<Child ...props onCreate={onCreate}/>
);
通常那不是最好的。Child
在这种情况下,仅传递实际需要的内容,val
并onCreate
:
return (
<Child val={props.val} onCreate={onCreate}/>
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句