Вот мое решение, которое почти такое же, как простая установка document.title
, но с использованием useEffect
/**
* Update the document title with provided string
* @param titleOrFn can be a String or a function.
* @param deps? if provided, the title will be updated when one of these values changes
*/
function useTitle(titleOrFn, ...deps) {
useEffect(
() => {
document.title = isFunction(titleOrFn) ? titleOrFn() : titleOrFn;
},
[...deps]
);
}
Это имеет преимущество в том, что повторный рендеринг возможен только в том случае, если вы изменили deps
.Никогда не перерисовывать:
const Home = () => {
useTitle('Home');
return (
<div>
<h1>Home</h1>
<p>This is the Home Page</p>
</div>
);
}
Перерисовывать только если мои userId
изменяются:
const UserProfile = ({ match }) => {
const userId = match.params.userId;
useTitle(() => `Profile of ${userId}`, [userId]);
return (
<div>
<h1>User page</h1>
<p>
This is the user page of user <span>{userId}</span>
</p>
</div>
);
};
// ... in route definitions
<Route path="/user/:userId" component={UserProfile} />
// ...
CodePen здесь, но не может обновить заголовок кадра
ЕслиВы проверяете <head>
кадра, вы можете увидеть изменения: ![screenshot](https://i.stack.imgur.com/wlosq.png)