【发布时间】:2018-09-05 12:40:03
【问题描述】:
componentDidMount 生命周期方法是否独立于兄弟组件?从下面的示例看来,它似乎只有在所有同级组件都已安装后才被调用。
假设我们有一个渲染 2 个子组件的顶级组件,第一个是简单的 render(),另一个是相对较慢的 render()。
要复制的样本:https://codesandbox.io/s/j43klml9py?expanddevtools=1
TL;DR:
class SlowComponent extends Component {
componentDidMount() {
// perf mark
}
render() {
// Simulate slow render
// Takes 50ms
return <h3>Slow component</h3>;
}
}
class FastComponent extends Component {
componentDidMount() {
// perf mark
}
render() {
return <h3>Fast component</h3>;
}
}
class App extends Component {
constructor(props) {
super(props);
// perf mark start
}
componentDidMount() {
// perf mark
// measure all marks and print
}
render() {
return (
<div>
<FastComponent />
<SlowComponent />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
我希望componentDidMount 的时间是这样的:
-
FastComponent10 毫秒 -
SlowComponent50 毫秒 -
App52 毫秒
但实际上我得到的是同时触发快速和慢速组件componentDidMount 回调,即
-
FastComponent50 毫秒 -
SlowComponent51 毫秒 -
App52 毫秒
当前示例和重现代码使用挂载回调,但同样适用于 componentDidUpdate。
完整来源:
import ReactDOM from "react-dom";
import React, { Component } from "react";
class SlowComponent extends Component {
componentDidMount() {
performance.mark("slow-mounted");
}
render() {
// Simulate slow render
for (var i = 0; i < 10000; i++) {
for (var j = 0; j < 100; j++) {
const b = JSON.parse(
JSON.stringify({
test: "test" + i,
test1: i * i * i
})
);
}
}
return <h3>Slow component</h3>;
}
}
class FastComponent extends Component {
componentDidMount() {
performance.mark("fast-mounted");
}
render() {
return <h3>Fast component</h3>;
}
}
class App extends Component {
constructor(props) {
super(props);
performance.mark("init");
}
componentDidMount() {
performance.mark("app-mounted");
performance.measure("slow", "init", "slow-mounted");
performance.measure("fast", "init", "fast-mounted");
performance.measure("app", "init", "app-mounted");
console.clear();
console.log(
"slow",
Math.round(performance.getEntriesByName("slow")[0].duration)
);
console.log(
"fast",
Math.round(performance.getEntriesByName("fast")[0].duration)
);
console.log(
"app",
Math.round(performance.getEntriesByName("app")[0].duration)
);
performance.clearMarks();
performance.clearMeasures();
}
render() {
return (
<div>
<h1>Demo</h1>
<FastComponent />
<SlowComponent />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
【问题讨论】:
-
快速回答:它们不是独立的。见stackoverflow.com/questions/32814970/…
-
那是在谈论父/子组件依赖,我目前的问题是关于子组件。
标签: javascript reactjs performance