reactjs如何动态切换render子组件

相关代码

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>
    );
  }
}

问题

  1. 如果获取的是'template_1',结果是没问题的,因为初始化的时候已经初始化了template_1

  2. 但如果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

阅读 5.8k
1 个回答

警告已经说的很明白,ShowName 在 render 的时候有调用到 setState,自己检查一下吧。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题