javascript-不带钩子更新文档标题

是否需要使用钩子来更新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]);

相关文章

kindeditor4.x代码高亮功能默认使用的是prettify插件,prett...
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小