[英]React hooks performance and best practices
在我的 React 應用程序中,我遇到了下一種情況。 在每個頁面上,我都必須創建這個邏輯:
const user = useUser();
const message = user.auth ? 'Welcome' : 'You are not allowed'
<Button>{message}</Button>
我必須在 10 頁上添加這個邏輯。 我知道我的問題更具理論性,但在我的情況下更好的是:
在每個頁面上添加此邏輯; 或者
創建一個像useButtonMessage()
這樣的自定義鈎子,如下所示:
export const useButtonMessage = () => { const user = useUser(); const message = user.auth ? 'Welcome' : 'You are not allowed' return message; }
如果只保留 3 行代碼,鈎子會不會是多余的?
就個人而言,我喜歡使用特定主題的所有相關事物創建掛鈎(而不是像message
這樣的常量)。 例如:
export const useAuth = () => {
const user = useUser()
const isLoggedIn = user.auth
const welcomeMessage = isLoggedIn ? 'Welcome' : 'You are not allowed'
/*
add selectors, functions to dispatch actions,
or other util contants such as welcomeMessage
*/
return {
isLoggedIn, // use this constant across your app to check if the user is logged in
user, // use this across your app to obtain the user
welcomeMessage,
};
}
我不會為此創建一個掛鈎,而是創建一個消息文件,其中將存儲應用程序的所有消息
然后你可以添加條件屬性 fe
export const messages =
{
userAllowed: (authenticated: boolean) => authenticated ? 'welcome' : 'you are not allowed'
}
你甚至可以更進一步:
export const messages =
{
Welcome: 'welcome',
NotAllowed: 'you are not allowed',
userAllowed: function(authenticated: boolean) {
return authenticated ? this.Welcome : this.NotAllowed
},
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.