![](/img/trans.png)
[英]react native setState in setInterval(), then setInterval executes error
[英]React Native: best practice to setInterval and Promises with setState in it
我目前正在與“無法在未安裝的組件錯誤上使用setState()或forceUpdate()”作戰,並且很難跟蹤錯誤來自哪個異步操作。 我懷疑是因為我使用setInterval
來增加秒數來顯示當前時間。 這是我在componentDidMount
, componentWillUpdate
和componentWillUnmount
中負責管理時間顯示的內容:
componentDidMount() {
this.mounted = true;
//listener to identify whether app is active/inactive
AppState.addEventListener('change', this.handleAppStateChange.bind(this));
//get user's intranet schedule
this.props.actionsMain.getSchedule(this.props.staff.staffID);
this.getLocation();
//After the first location received, re-check every 20 seconds
this.locationInterval = setInterval(() => {
this.getLocation();
}, 20000);
}
componentDidUpdate() {
//when we just received server time, parse and set the time to state, then set the interval timer
if (this.props.scheduleReceived && this.state.time[0] === null) {
let time = this.props.schedule['time_server'].split(':'),
hh = parseInt(time[0]) + this.props.location.zone,
mm = parseInt(time[1]),
ss = parseInt(time[2]);
if (this.mounted) {
this.setState({ time: [hh, mm, ss] });
this.serverTimeInterval = setInterval(() => {
let { time } = this.state, hh = time[0], mm = time[1], ss = time[2];
//add second and adjust time
ss += 1;
if (ss >= 60) {
ss -= 60;
mm += 1;
if (mm >= 60) {
mm -= 60;
hh += 1;
if (hh >= 24)
hh -= 24;
}
}
if (this.mounted)
this.setState({ time: [hh, mm, ss] })
}, 1000)
}
}
}
componentWillUnmount() {
//Remove all timer events
clearInterval(this.serverTimeInterval);
clearInterval(this.locationInterval);
//Remove listener
AppState.removeEventListener('change', this.handleAppStateChange.bind(this));
this.mounted = false;
}
誰能指出我在這里做錯了的事情,即使我正在做的事情也是一種很好的做法?
同樣,我的第二個懷疑來自於從setInterval()
執行並返回到未安裝組件的獲取位置承諾。 如果有任何經驗法則可以遵循,我將如何確保setInterval,setState和Promises和諧地工作,那真是太棒了!
提前致謝!
您永遠不要在componentDidUpdate中調用setState,這將導致無限循環
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.