[英]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.