我正在使用Redux动作来获取Google几何数据。我对此有疑问。重定向到新页面时,我收到警告消息:警告:无法在已卸载的组件上调用setState(或forceUpdate)。这是空操作,但它表明应用程序中发生内存泄漏。要修复此问题,请取消componentWillUnmount方法中的所有订阅和异步任务。
实际上,我对React很陌生。谁能帮我解决这个问题?
以下是我到目前为止构建的代码。
class BranchList extends Component {
startInterval;
state = {
city: "",
_isMounted: false
};
setTodayWeatherInfo = city => {
// invoke actions with parameter, city
// once I remove this one, no warning message generated
this.props.setLocation(city);
this.props.additionalTodayWeatherInfo(city);
if (this.startInterval) clearInterval(this.startInterval);
this.startInterval = setInterval(() => {
this.props.additionalTodayWeatherInfo(city);
}, 300000);
};
componentDidMount() {
const city = sessionStorage.branch_city || options[0].value;
this.setState({
city,
_isMounted: true
});
this.setTodayWeatherInfo(city);
}
shouldComponentUpdate(nextProps, nextState) {
return this.state.city !== nextState.city ? true : false;
}
componentWillUnmount() {
this.setState({ _isMounted: false });
clearInterval(this.startInterval);
this.startInterval = false;
}
render() {
if (!this.state.city) return <div />;
//this.props.location(this.state.city);
return (
<div>
<nav className="navbar navbar-expand-sm bg-warning">
<div className="text-center w-100">
<h4>Welcome to Korean Restaurant in {`${this.state.city}`}</h4>
</div>
<div className="mx-auto text-center w-50">
<SelectCity
setCity={city => {
this.setState({ city });
this.setTodayWeatherInfo(city);
}}
refreshStatus={this.props.refreshStatus}
/>
</div>
</nav>
</div>
);
}
}
export default connect(
null,
{ additionalTodayWeatherInfo, setLocation }
)(BranchList);
然后,this.props.setLocation(city)调用操作如下。一旦摆脱this.props.setLocation(city),它不会生成警告消息。不过,我需要放弃一些与此相关的功能。
export function setLocation(branch_city) {
const url = `${GoogleURL}=${branch_city}&key=${
process.env.REACT_APP_GMAP_API_KEY
}`;
const request = axios.get(url);
return {
type: FETCH_LOCATION,
payload: request
};
} 有什么方法可以防止警告消息?
答案 0 :(得分:0)
我不知道this.props.setLocation(city)到底是做什么的,但是我相信它肯定会影响DOM,这里的问题是,即使退出这个BranchList组件,您仍在尝试更改组件不再存在于DOM中,就像您在componentWillUnmount方法中清除setInterval的方式一样,尝试停止调用setLocation方法