javascript - 在父类传递的事件处理程序中有条件地更新子组件的状态
问题描述
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(粗体部分)中函数的请求后部分移到可由子类调用的父组件。这个想法是使组件抽象并可由其他类似的父类重用。
解决方案
Create the function in the parent, and pass it to the child in the props:
const Parent = (props) => {
// The handler
const onCreate = /*...*/;
// some other stuff
return (
<Child ...props onCreate={onCreate}/>
);
}
Then have the child call the function with any parameters it needs (there don't seem to be any in your example, you're not using val
in it for instance):
return (
<MaterialTable
title={props.title}
data={val}
editable={{
onRowAdd: props.onCreate // Or `onRowAdd: () => props.onCreate(parameters, go, here)`
}}
/>
);
Side note: There's no reason to copy props.val
to val
state member within the child component, just use props.val
.
Side note 2: Destructuring is often handy with props:
const Child = ({val, onCreate}) => {
// ...
};
Side note 3: You have your Parent
component calling Child
with all of its props, via ...props
:
return (
<Child ...props onCreate={onCreate}/>
);
That's generally not best. Only pass Child
what it actually needs, in this case, val
and onCreate
:
return (
<Child val={props.val} onCreate={onCreate}/>
);
推荐阅读
- python - python多对话框中超出的最大递归深度
- javascript - 如何在 Webpack 中渲染 ejs 文件
- java - 我怎样才能使信息屏幕像这个应用程序中的一样
- javascript - 如何在 Mirth 中转换带有两个段的 HL7 消息
- javascript - websocket工作但没有更新我的html表
- laravel - 在 Mac 上安装 Laravel 时缺少 PHP 扩展
- java - 为什么我传递给 Arrays.sort 的方法引用必须是静态的?
- python - 无法在 nginx 中加载媒体文件
- javascript - React Compound Components 类型警告
- sql - 在 Laravel 迁移中添加系统版本异常