Created
October 26, 2016 05:45
-
-
Save mohayonao/b9971996acef70755151d9926700be8b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { Component, PropTypes } from "react"; | |
| import Volatile from "./Volatile"; | |
| @Volatile({ timeout: 2500 }) | |
| class UI extends Component { | |
| static propTypes = { | |
| data: PropTypes.number.isRequired, | |
| }; | |
| shouldComponentUpdate(nextProps) { | |
| return nextProps.data !== this.props.data; | |
| } | |
| rener() { | |
| return (<div>{ this.props.data }</div>); | |
| } | |
| } | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React from "react"; | |
| export default function Volatile(opts = { timeout: 1000 }) { | |
| return (Component) => { | |
| return class VolatileComponent extends React.Component { | |
| constructor(props) { | |
| super(...props); | |
| this.state = { visible: false }; | |
| this._timerId = 0; | |
| } | |
| componentWillReceiveProps(nextProps) { | |
| if (this::Component.prototype.shouldComponentUpdate(nextProps)) { // <- !!?!?!?!???!? | |
| this.setState({ visible: true }); | |
| clearTimeout(this._timerId); | |
| this._timerId = setTimeout(() => { | |
| this.setState({ visible: false }); | |
| }, opts.timeout); | |
| } | |
| } | |
| shouldComponentUpdate(_, nextState) { | |
| return nextState.visible || (nextState.visible !== this.state.visible); | |
| } | |
| render() { | |
| if (!this.state.visible) { | |
| return null; | |
| } | |
| return (<Component { ...this.props }/>); | |
| } | |
| }; | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment