我创建了一个简单的吐司,它在第一次工作,但是当我第二次单击它时,它不起作用,我也不知道为什么它不起作用。我试图寻找其他答案,但没有发现有人提出任何建议。
让我们看一下代码
我的吐司成分
export class Toast extends PureComponent<any> {
state = {
timePassed: false
};
componentDidMount() {
setTimeout( () => {
this.setTimePassed();
},2000);
clearTimeout()
}
setTimePassed() {
this.setState({timePassed: true});
}
render() {
const { color, title, subtitle } = this.props
if (this.state.timePassed){
return '';
}else{
return (
<div className="toast">
<p>{title}</p>
<div>{subtitle}</div>
</div>
);
}
}
这是用法
export class Product extends PureComponent<any> {
state = {
like: true,
icon: <Icon.HeartEmpt/>,
toast: ''
}
handleClick() {
this.setState({like: !this.state.like})
if (this.state.like) {
this.setState({toast: <Toast color='green' title='Produto adicionado' subtitle='Produto adicionado aos favoritos'/>})
} else {
this.setState({toast: <Toast color='red' title='Produto removido' subtitle='Produto removido dos favoritos'/>})
}
}
render() {
return (
<>
<div className='product'>
{this.state.toast}
</div>
</>
)
}
}
您应该在Parent
组件而不是组件上处理Toast消失Toast
。因此您在触发setTimeout Product
。不要像@ c0mit所说的那样在商店中存储JSX组件。
我也会删除烤面包的状态。因为它取决于like
,所以我将其内容存储在一个对象上并通过like
值(即为added
or removed
)进行访问。
您还需要确保在卸载组件时清除setTimeout。并在componentDidUpdate触发setTimeout,但是需要检查它是否未触发setTimeout以及disPlayToast是否为true
。
export class Toast extends PureComponent<any> {
render() {
const { color, title, subtitle } = this.props
return (
<div className="toast">
<p>{title}</p>
<div>{subtitle}</div>
</div>
);
}
}
const toastProps = {
liked: {
color:'green',
title:'Produto adicionado',
subtitle:'Produto adicionado aos favoritos'
},
removed: {
color:'red',
title: 'Produto removido',
subtitle:'Produto removido dos favoritos'
}
}
class Product extends PureComponent<any, any> {
state = {
like: 'removed',
displayToast: false
}
// timeHandler to store setTimeout
timerHandle = 0
componentDidUpdate() {
// to trigger setTimeout validate that Toast is on display
// and timerHandle
if(this.state.displayToast && !this.timerHandle){
this.timerHandle = setTimeout(() => {
this.setState({ displayToast: false });
// clear timerHandle
this.timerHandle = 0;
},2000);
}
}
componentWillUnmount = () => {
// clearTimeout if it's running
if (this.timerHandle) {
clearTimeout(this.timerHandle);
this.timerHandle = 0;
}
};
handleClick = () => {
this.setState(( { like } ) => ({
like: like === 'liked' ? 'removed' : 'liked',
displayToast: true })
)
}
render() {
const {like, displayToast} = this.state
return (
<div>
<button onClick={this.handleClick}>filp</button>
<div className='product'>
{displayToast && <Toast {...toastProps[like]} />}
</div>
</div>
)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句