使用继承的ES6 React类时未触发componentDidMount方法 [英] componentDidMount method not triggered when using inherited ES6 react class

查看:147
本文介绍了使用继承的ES6 React类时未触发componentDidMount方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在React内使用ES6类,并希望我的所有组件都继承某些方法,但是,当我尝试扩展可扩展React.Component类的组件时,componentDidMount方法不会触发因此,没有任何东西呈现出来.我正在使用的代码:

I'm trying to use ES6 classes inside of React, and want all my components to inherit certain methods, however as soon as I try to extend a component which extends the React.Component class, the componentDidMount method doesn't trigger and hence nothing gets rendered. The code I'm using:

BaseComponent.jsx

BaseComponent.jsx

import React from 'react';

class BaseComponent extends React.Component {

    constructor() {
        super();   
        console.log('BaseComponent constructor');
     }

     render() {
         return (
             <div>Hello, Im the base component</div>  
         );
     }
}

export default BaseComponent;

ExampleComponent.jsx

ExampleComponent.jsx

import BaseComponent from './BaseComponent';

class ExampleComponent extends BaseComponent {
     constructor(props) {

        super(props);
     }

     componentDidMount() {
         console.log('exampleComponent mounted');
     }

    render() {
        return (
            <div>Hello, Im the example component</div>  
        );
    }
}

export default ExampleComponent;

App.jsx

import React from 'react';
React.render(<ExampleComponent />, document.body);

我正在使用React 0.13.3,并使用babelify 6.1.2进行转译.

I'm using React 0.13.3, and using babelify 6.1.2 to transpile.

字符串"exampleComponent Mounted"永远不会登录到控制台,因此不会呈现任何内容.有什么想法我做错了吗?

The string 'exampleComponent mounted' never gets logged to console, and nothing is rendered. Any ideas what I'm doing wrong?

推荐答案

我不确定这种方法,但是此代码也可以工作:

I'm not sure about the approach, but this code also works:

export default class Service extends BaseComponent {
  componentDidMount(...args) {
    super.componentDidMount.apply(this, args);
  }
}

UPD:但是,这被认为是不好的做法:

UPD: this is considered to be a bad practice though:

a) https://medium .com/@ dan_abramov/how-to-to-use-classes-and-sleep-at-night-9af8de78ccb4 b) https://medium.com/@ dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750

这篇关于使用继承的ES6 React类时未触发componentDidMount方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆