代码之家  ›  专栏  ›  技术社区  ›  Fellow Stranger

在AJAX响应后显示消息n秒

  •  1
  • Fellow Stranger  · 技术社区  · 6 年前

    class FlashMessage extends Component {
      state = { visible: false }
    
      updateVisibility = () => {
        this.setState({ visible: true }, () =>
          this.setTimeout(this.setState({ visible: false }), 5000)
        )
      }
    
      render() {
        this.updateVisibility()
        if (this.props.data && this.state.visible) {
          return <div>Saved!</div>
        }
        return false
      }
    }
    
    export default FlashMessage
    

    上面是我徒劳的尝试创建一个这样做的组件,但显然不起作用,因为您:

    无法在现有状态转换期间更新(例如在 render

    不幸的是我不能依靠 onClick 在这里。

    2 回复  |  直到 6 年前
        1
  •  2
  •   Fellow Stranger    6 年前

    class FlashMessage extends Component {
      state = { visible: false }
    
      componentWillMount(){
        this.setState({ visible: true });
      }
    
      componentDidMount(){
        this.timer = this.setTimeout(()=> {this.setState({ visible: false })}, 5000)
      }
    
      componentWillUnMount(){
        clearTimeout(this.timer);
      }
    
      render() {
        return(
            <div>
                {this.props.data && this.state.visible ? "Yes, data received!" : "Data not received"}
            </div>
        )
      }
    }
    
    export default FlashMessage;
    

    请不要在最新的react版本中弃用componentWillMount,但如果不想使用componentWillMount,也可以使用构造函数

    如果您对以上代码有任何疑问,请告诉我。

        2
  •  0
  •   obiwankenoobi    6 年前

    这是一个非常棘手的概念,因为您无法更改渲染时的状态。我强烈建议你用图书馆来做这件事。在我的情况下,我使用 react-alert