不调用parent的componentDidMount()

时间:2017-06-27 13:53:28

标签: javascript reactjs inheritance ecmascript-6

我有BaseComponent,所有其他组件都从该组件继承。但是,如果子组件具有componentDidMount(),则不会调用父级componentDidMount()。是否有任何方法可以在componentDidMount()子组件之后始终调用父组件的componentDidMount()?这是example

2 个答案:

答案 0 :(得分:0)

您可以使用“super()”函数来调用父实现。

componentDidMount() {
    console.log('Child mounted.');
    super();
}

这被视为反模式。建议的方法是组合(详情here)。不幸的是,如果不知道你想要通过继承来实现什么,我们就无法通过组合告诉你一个替代方案。在使用您的示例时,可以执行类似这样的操作

class Animal extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        console.log('Parent mounted.'); // Not working.
    }

    render() {
        return (<div>{this.props.animalType}</div>);
    }
}

class Dog extends React.Component {
    componentDidMount() {
        console.log('Child mounted.');
    }

    render() {
        return (<Animal animalType="Dog" />);
    }
}

React.render(<Dog />, document.body);

答案 1 :(得分:0)

在您的示例中,您的父组件Animal实际上不是父组件,而是一个独立组件,因为无论如何您正在呈现Dog组件。

这是componentDidMount组件Animal没有被调用的原因,实际上Animal component本身没有被渲染,只是被定义。

为了使Dog成为Animal组件的子组件,请从父组件(Animal)中呈现它并更改代码,如

class Animal extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        console.log('Parent mounted.'); // Not working.
    }
    render() {
    return (
         <Dog/>
    )

    }

}

class Dog extends Animal {
    componentDidMount() {
        console.log('Child mounted.');
    }

    render() {
        return <div>Dog.</div>;
    }
}
React.render(<Animal />, document.body);

<强> JSFIDDLE