异步触发一个shouldComponentUpdate?

时间:2016-07-21 13:41:13

标签: javascript reactjs

假设我有一个Timestamp组件,应该每6000毫秒更新一次。这是基地:

class Timestamp extends Component {
  static propTypes = {
    timestamp: PropTypes.date.isRequired
  };
  render() {
    const { timestamp } = this.props;
    return (
      <div className="timestamp">
        {moment(timestamp).fromNow()}
      </div>
    )
  }
}

我已经阅读了lifecycle of a react component,看起来shouldComponentUpdate就像我想要的那样 - 但是,似乎没有一种异步方式来应用它。例如:

shouldComponentUpdate() {
  const { timestamp } = this.props;
  this._timer = setInterval(() => {
    // need to update
  })
}

如何做出反应?

2 个答案:

答案 0 :(得分:1)

仅考虑React,可以使用setState()或使用forceUpdate(您应该避免)来更新组件。

在这两种情况下,shouldComponentUpdate都不应该这样做。将setInterval(()放入componentDidMount(){}

答案 1 :(得分:1)

在这种情况下,componentDidMountsetInterval调用setState中更好的启动计时器会触发重新呈现

class Timestamp extends React.Component {

  constructor() {
    super();
    
    this._timer = null;
    this.state = { timestamp: Date.now() };
  }
 	 
  componentDidMount() {
    this._timer = setInterval(() => this.onChangeTimestamp(), 6000);
  }
  
  componentWillUnmount() {
    clearInterval(this._timer);
  }
  
  onChangeTimestamp() {
    this.setState({ timestamp: Date.now() }) 
  }
  
  render() {
    return (
      <div className="timestamp">
        { new Date(this.state.timestamp).toString() }
      </div>
    )
  }
}

ReactDOM.render(
  <Timestamp />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>