【发布时间】:2019-04-14 16:31:42
【问题描述】:
根据文档:
componentDidUpdate()在更新发生后立即被调用。初始渲染不调用此方法。
我们可以使用新的useEffect() 钩子来模拟componentDidUpdate(),但似乎useEffect() 在每次渲染后都会运行,即使是第一次。如何让它不在初始渲染时运行?
正如您在下面的示例中所见,componentDidUpdateFunction 在初始渲染期间打印,但componentDidUpdateClass 在初始渲染期间未打印。
function ComponentDidUpdateFunction() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log("componentDidUpdateFunction");
});
return (
<div>
<p>componentDidUpdateFunction: {count} times</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
class ComponentDidUpdateClass extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
componentDidUpdate() {
console.log("componentDidUpdateClass");
}
render() {
return (
<div>
<p>componentDidUpdateClass: {this.state.count} times</p>
<button
onClick={() => {
this.setState({ count: this.state.count + 1 });
}}
>
Click Me
</button>
</div>
);
}
}
ReactDOM.render(
<div>
<ComponentDidUpdateFunction />
<ComponentDidUpdateClass />
</div>,
document.querySelector("#app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
【问题讨论】:
-
我可以问一下,当基于渲染次数而不是像
count这样的显式状态变量来做某事是有意义的时候,用例是什么? -
@Aprillion,在我的情况下,更改 H2 的内容,其中包含需要在项目列表之后更改的文本,它是空的,并且在开始时甚至不同。在从 API 获取数据之前,相同的列表在开始时也是空的,因此对于基于数组长度的正常条件渲染,初始值会被覆盖
标签: javascript reactjs react-hooks