Reactjs 用计时器重新加载子对象
当各种父组件将数据提交到服务器时,会出现一个保存提示。保存提示是一个非常简单的组件:Reactjs 用计时器重新加载子对象,reactjs,Reactjs,当各种父组件将数据提交到服务器时,会出现一个保存提示。保存提示是一个非常简单的组件: export class PromptComponent extends React.Component<{}, {}> { constructor(props: any) { super(props) } public render(): JSX.Element { return ( <div> {this.props.showA
export class PromptComponent extends React.Component<{}, {}> {
constructor(props: any) {
super(props)
}
public render(): JSX.Element {
return (
<div>
{this.props.showAlert ? (
<div id='alert-prompt'>
<span>{this.props.children}</span>
</div>
) : null}
</div>
)
}
}
所以,如果我必须将此代码放入每个父级,并让它们跟踪警报状态,那么这将变得多余。有没有更有效的方法用更少的代码来实现这一点?理想情况下,我希望将依赖计时器的状态移动到实际的警报组件本身。定义一个回调useCallback props函数以在子组件中使用
检查:
类应用程序扩展了React.Component{
渲染{
回来
{
设置超时=>{
回调;
}, 1000;
}}
>
你好
;
}
}
将显示状态移动到子组件并使用回调:
导出默认类PromptComponent扩展React.Component{
状态={
秀:真的
};
组件安装{
this.props.showarter=>this.setState{show:false};
}
渲染{
回来
{this.state.show&&
{this.props.children}
}
;
}
}
通过这种方式,您可以将状态与父组件解耦,而且您的回调也是一个通用回调,因此在将来,您可以将其更改为setInterval或其他任何内容
哇,这正是我想要的。非常感谢。
const closeAlert = () => {
const closeModal = () => this.setState({
showAlert: false,
})
setTimeout(closeModal, 1000)
}
this.setState(
{
showAlert: true,
},
() => closeAlert()
)