这真的让我发疯,我不知道这里出了什么问题。我有一个滑块,每次单击一张幻灯片时,我都想获取当前的活动索引。基于当前索引,我想设置状态。.但我一直在保持最大更新深度。
state = {
profiles: profileData,
educations: educationData,
selectedProfile: localStorage.getItem('slug'),
selectedEducation: localStorage.getItem('sector') || '',
popupActive: false,
profileSelected: true,
sector: 'Zorg',
showVideo: true,
primaryImg: Timmerman,
redirect: false,
defaultImage: Default,
noSector: Tijdelijk,
slideActive: true,
playState: false,
primaryVid:
'https://localhost.web/videos/desktop/fase2/NPRZ_ADB_Video_2_1_V2.mp4',
thumbIndex: 0,
showTumbs: false,
};
componentDidUpdate() {
if (this.state.slideActive === true) {
console.log('Thumbs showing');
this.setState({
slideActive: false,
});
}
}
// Switch the primary splashscreen and vid src with the image clicked
switchPrimary = e => {
this.setState({
primaryImg: e.target.style.backgroundImage.split(/"/)[1], // get the data so that it can be passed on to the child component
primaryVid: e.target.getAttribute('data'), // get the data so that it can be passed on to the child component
slideActive: true,
thumbIndex: e.currentTarget.getAttribute('data-index'),
playFromThumb: true,
showTumbs: false,
});
// console.log('hiding:', this.state.showTumbs);
// console.log('actief');
// if (this.state.showTumbs === false) {
// this.setState({
// showTumbs: true,
// });
// }
};
答案 0 :(得分:3)
您正在检查状态slideActive
在componentDidUpdate
中是否为真,是否正在调用setState
,这将导致对componentDidUpdate
的新调用,并且循环继续。
您还希望检查slideActive
与上次更新之间的实际差异。
componentDidUpdate(prevProps, prevState) {
if (prevState.slideActive !== this.state.slideActive && this.state.slideActive) {
console.log("Thumbs showing");
this.setState({
slideActive: false
});
}
}
答案 1 :(得分:0)
您应该将逻辑放在componentDidMount
中,以比较旧状态与新道具或旧道具与新道具的状态,以避免出现这种情况:
您可以立即在componentDidUpdate()中调用setState(),但请注意,必须将它包装在一个条件中,否则将导致无限循环。
更多阅读内容和示例:React ComponentDidUpdate()