Warning: Can't call setState on a component that is not yet mounted.
来源:8-7 【i18n】完成网站语言切换

KyungLee
2021-08-29
啊老师您好,Header.class.tsx 里类 HeaderComponent
的构造函数调用了 store.subscribe(this.handleStoreChange);
,而handleStoreChange
函数里又调用了 setState
:
this.setState({
language: storeState.language,
languageList: storeState.languageList,
});
这会在浏览器开发者工具的 console 里面引起警告:
Warning: Can’t call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to
this.state
directly or define astate = {};
class property with the desired state in the HeaderComponent component.
请问要怎么处理呢?
我把 store.subscribe(this.handleStoreChange);
提出来放到 componentDidMount()
里面,警告就消失了,请问这样是否规范呢?
componentDidMount() {
store.subscribe(this.handleStoreChange);
}
写回答
1回答
-
阿莱克斯刘
2021-09-07
你的改动合乎规范,而课程为了讲解方便反而不符合规范。不过,也不用太在意,因为在真实项目中,我们一般都不会直接使用订阅模式,而是通过react-redux来订阅store。
10
相似问题