是否需要使用钩子来更新document.title?与仅按如下所示直接设置标题相比,使用useEffect有什么好处吗?
(此代码段还将标题回显到控制台,因为您无法在Stack Snippets中看到文档标题,但是在我的真实代码中,我只是在更新标题.)
const { useState } = React;
function Example() {
const [count,setCount] = useState(0);
document.title = `You clicked ${count} times`;
console.log(document.title);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
ReactDOM.render(<Example />,document.getElementById('app'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="app"></div>
(注意:这是useEffect
example,没有useEffect调用.)
最佳答案
Is it required to use a hook for updating document.title?
不可以,因为两次设置标题不会造成任何伤害.
Is there any advantage to using useEffect vs. just setting the title directly as below?
如果正确使用了Effect,则仅在计数实际更改时才更新标题.但是,由于组件中只有一种状态,因此只有在更新计数后才会重新呈现,因此在这种情况下没有任何区别.
如果向下滚动,您将看到您提到的教程最后将其更改为此(将执行我刚才描述的操作):
useEffect(() => {
document.title = `You clicked ${count} times`;
},[count]);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。