gpt4 book ai didi

reactjs - setState(...) : Can only update a mounted or mounting component. 这通常意味着您在未安装的组件上调用了 setState()。这是一个无操作

转载 作者:行者123 更新时间:2023-12-03 12:54:31 26 4
gpt4 key购买 nike

componentDidMount(prevProps, prevState, prevContext) {
let [audioNode, songLen] = [this.refs.audio, List.length-1];

audioNode.addEventListener('ended', () => {
this._endedPlay(songLen, () => {
this._currSong(this.state.songIndex);
this._Play(audioNode);
});
});

audioNode.addEventListener('timeupdate', () => {
let [remainTime, remainTimeMin, remainTimeSec, remainTimeInfo] = [];

if(!isNaN(audioNode.duration)) {
remainTime = audioNode.duration - audioNode.currentTime;
remainTimeMin = parseInt(remainTime/60); // 剩余分
remainTimeSec = parseInt(remainTime%60); // 剩余秒

if(remainTimeSec < 10) {
remainTimeSec = '0'+remainTimeSec;
}
remainTimeInfo = remainTimeMin + ':' + remainTimeSec;
this.setState({'time': remainTimeInfo});
}
});
}

componentWillUnmount () {
let audio = this.refs.audio;
audio.removeEventListener('timeupdate');
audio.removeEventListener('ended');
}

错误:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.

我在componentWillUnmount中“结束”了removeEventListener,但它不起作用。因为我在 componentDidMount 中添加了 this.setState({'time': keepTimeInfo});

最佳答案

我通过为组件分配一个 ref 解决了这个问题,然后在设置状态之前检查该 ref 是否存在:

myMethod(){
if (this.refs.myRef)
this.setState({myVar: true});
}

render() {
return (
<div ref="myRef">
{this.state.myVar}
</div>
);
}

最近,由于我主要使用功能组件,因此我使用这种模式:

const Component = () => {
const ref = React.useRef(null);
const [count, setCount] = React.useState(0);

const increment = () => {
setTimeout(() => { // usually fetching API data here
if (ref.current !== null) {
setCount((count) => count + 1);
}
}, 100);
};

return (
<button onClick={increment} ref={ref}>
Async Increment {count}
</button>
);
};

关于reactjs - setState(...) : Can only update a mounted or mounting component. 这通常意味着您在未安装的组件上调用了 setState()。这是一个无操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34544314/

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