【发布时间】:2019-11-21 23:48:56
【问题描述】:
我目前正在查看 react doc 的 useEffect 示例
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
我的问题是我们可以轻松地为按钮制作一个 handleClick 函数。我们不必使用 useEffect
const handleButtonClick = () =>{
setCount(count+1)
document.title = `You clicked ${count +1} times`
}
<button onClick={handleButtonClick}/>
那么哪种方式被认为是好的做法?是否最好只使用 useEffect 来触发严格无法与主效果一起完成的副作用(即组件接收新道具时)
【问题讨论】:
-
好问题它也让我感到困惑,我看到的例子并没有真正显示出它的优势。
标签: reactjs