其他单击后函数setTimeout不起作用

爱德华多·克拉赫克(Eduardo Krakhecke)

我创建了一个简单的吐司,它在第一次工作,但是当我第二次单击它时,它不起作用,我也不知道为什么它不起作用。我试图寻找其他答案,但没有发现有人提出任何建议。

让我们看一下代码

我的吐司成分

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值(即为addedor 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>
        )
    }
}

https://stackblitz.com/edit/so-toast-timeout?file=index.tsx

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章