相关代码
export default class MyPage extends React.Component{
constructor(props){
this.state={
Name:'template1',
config:{}
}
}
componentDidMount(){
hleper.ajax({url:''}).then((reps)=>{
this.setState({
Name:reps.Name
});
});
}
getComponents() {
let _self = this;
let _state = _self.state;
switch (_state.Name) {
case 'template_1':
return <TemplateOne config={_state.config} />;
case 'template_2':
return <TemplateTwo config={_state.config} />;
default:
return <TemplateOne config={_state.config} />;
}
}
render() {
return (
<div className={ `container` }>
<div>
{this.getComponents()}
</div>
</div>
);
}
}
问题
如果获取的是'template_1',结果是没问题的,因为初始化的时候已经初始化了template_1
但如果ajax获取的是template_2,则需要渲染template2对应的组件,结果也能出来,但是会报warning
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the ShowName component.
ShowName是templateTwo中的组件
疑问:
该如何动态切换组件,并且不报warning
警告已经说的很明白,
ShowName
在 render 的时候有调用到setState
,自己检查一下吧。