gpt4 book ai didi

javascript - 异步触发 shouldComponentUpdate?

转载 作者:行者123 更新时间:2023-11-30 15:56:06 25 4
gpt4 key购买 nike

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

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
})
}

这个在react中应该怎么实现?

最佳答案

在这种情况下,最好在 componentDidMount 中启动计时器,并在 setInterval 中调用触发重新渲染的 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>

关于javascript - 异步触发 shouldComponentUpdate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38505932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com