1) 确保您在 componentDidMount 中拥有任何 event listeners, setTimeouts or setIntervals 并在 componentDidMount 中删除它们强>componentWillUnmount
监听器、setTimeouts 和 setIntervals 的示例:
componentDidMount() {
this.myTimer = setTimeout(() => {
// someCode here
}, 7000);
AppState.addEventListener('change', this.handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this.handleAppStateChange);
clearTimeout(this.myTimer);
}
2) 要取消提取,您有以下选择:
选项A:使用AbortController
(在我看来,AbortController 比带有 isMounted 变量的旧解决方案要好得多)
AbortController 示例:
import "abortcontroller-polyfill"; // in RN 0.60+ this will probably not be needed anymore
class App extends React.Component {
constructor() {
const AbortController = window.AbortController;
this.controller = new AbortController();
this.signal = this.controller.signal;
}
componentDidMount() {
const url = "https://myurl.com";
const signal = this.signal;
fetch(url, { signal })
.then(res => res.json())
.then(json => console.log(json))
.catch(err => {
// You can catch the error
// thrown by the polyfill here.
if (err.name == "AbortError") {
console.log("Fetch Aborted");
} else {
//Catch other errors.
}
});
}
componentWillUnmount() {
this.controller.abort();
}
/*--Rest of the code.--*/
}
选项 B:使用Axios 并在componentDidMount 中触发取消
https://github.com/axios/axios#cancellation
来源:
AbortController 代码:
https://github.com/facebook/react-native/issues/18115#issuecomment-420766665
How to cancel a fetch on componentWillUnmount
https://developer.mozilla.org/en-US/docs/Web/API/AbortController