gpt4 book ai didi

javascript - 更改站点时停止间隔功能

转载 作者:行者123 更新时间:2023-11-30 20:14:04 25 4
gpt4 key购买 nike

我正在使用 react 编写网站.在一个组件中,我有一个 setInterval()执行的函数,它会更新它们 DOM .现在,当我使用路由器 ( react-router-dom ) 切换到另一个站点时, setInterval()函数崩溃,因为它找不到 DOM要更新的元素。我该如何继续呢?我虽然我使用 componentWillUnmount()但出现同样的错误。

class Counter extends React.Component {
constructor(props) {
super(props);

this.state = {
stop: false,
}
}

componentWillUnmount() {
if(!this.state.stop) {
this.setState({
stop: true,
})
}
}

_stop = (counter) => {
clearInterval(counter);
}

_someFunc = () => {
...
}

render() {
...
const update = setInterval(function () {
document.getElementById('some-id').innerText = this._someFunc();
}, 1000);

if(this.state.stop) {
this._stop(update)
}

return (
<p id='some-id'></p>
)
}
}

export default Counter;

TypeError: document.getElementById(...) is null.

如何停止间隔?

最佳答案

变化:

1- 将计时器放在渲染方法之外,最好使用 componentDidMount 生命周期方法。通过这种方式,定时器将只被注册一次,并且在每 1ms 之后它会执行回调方法。

2- 将计时器 ID 存储在一个变量中(例如)以在离开页面之前停止它。

像这样:

class Counter extends React.Component {
constructor(props) {
super(props);

this.state = {
stop: false,
}
}

componentDidMount() {
this.timerId = setInterval(function () {
document.getElementById('some-id').innerText = this._someFunc();
}, 1000);
}

componentWillUnmount() {
this._stop();
}

_stop = () => {
clearInterval(this.timerId);
}

_someFunc = () => {
...
}

render() {

return (
<p id='some-id'></p>
)
}
}

export default Counter;

关于javascript - 更改站点时停止间隔功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52098689/

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