시점 이동 줄이기 | Frontend Fundamentals #82
Replies: 3 comments 4 replies
-
|
좋은 글 잘읽었습니다. 아래는 A. 조건을 펼쳐서 그대로 드러내기의 또다른 구현입니다. Solidjs의 Switch, Match 컴포넌트의 영향을 받았습니다. 결과 먼저 보여드리겠습니다. function Page() {
const user = useUser();
return (
<Switch>
<Case when={user.role === "admin"}>
<div>
<Button disabled={false}>Invite</Button>
<Button disabled={false}>Read</Button>
</div>
</Case>
<Case when={user.role === "viewer"}>
<div>
<Button disabled={true}>Invite</Button>
<Button disabled={false}>Read</Button>
</div>
</Case>
<Case isDefault>{null}</Case>
</Switch>
)switch문 역할을 하는 유틸 컴포넌트 Switch와 Case를 추가하였습니다. type CaseType = {
when?: boolean;
isDefault?: boolean;
};
const Case = ({
children,
}: CaseType & { children: React.ReactNode }): React.ReactNode => {
return children;
};
const Switch = ({
children,
}: {
children: React.ReactElement<CaseType>[];
}): React.ReactNode => {
const defaultComponent = children.find((child) => child?.props?.isDefault);
const resultComponent = children.find((child) => child?.props?.when);
return resultComponent || defaultComponent;
}; |
Beta Was this translation helpful? Give feedback.
-
|
안녕하세요. 예제 코드에 대해 질문이 있습니다.
해당 코드에서 policy 객체가 컴포넌트 내부에서 선언되기 때문에, 렌더링될 때마다 객체가 생성되고 제거되어 메모리 사용이 반복될 것으로 보입니다. 그래서 다음처럼 객체를 컴포넌트 외부 상수로 분리하는 방식이 더 효율적이지 않을까 고민이 됩니다: 다만 이렇게 되면 그래서 궁금한 점은 다음과 같습니다:
|
Beta Was this translation helpful? Give feedback.
-
|
개인적으로 B안이 좀 더 매력적인 것 같은데요, 그 이유는 A안은 구조적으로 코드가 반복될 뿐만 아니라 실제로도 조건의 상태가 변화할 때 렌더링할 Button 컴포넌트가 unmount되고 새로 mount되는 과정이 반복되어 인터랙션이 엮여있는 케이스에는 좋지 않을 것으로 보이기 때문입니다. 상태를 가지고 돔을 다룬다라는 React의 컨셉에도 B안이 더 적절해보여요. 여기서 B안을 조금 더 개선하자면 function Page() {
const user = useUser();
const policy = getPolicyByRole({
admin: { canInvite: true, canView: true },
viewer: { canInvite: false, canView: true }
}, user.role)
return (
<div>
<Button disabled={!policy.canInvite}>Invite</Button>
<Button disabled={!policy.canView}>View</Button>
</div>
);
}위와 같이 policy를 객체로만 선언하는 것보다 유틸 함수로 한 번 감싸주어 보다 type-safe하게 다루는 건 어떨까 싶습니다. Object[user.role] 이 구조가 개인적으로는 가독성이 좋지 않아보이기도 하고, role이 무엇인지가 드러나지 않는 날 것의 객체이기 때문에 약속된 구조를 함수를 통해 강제하는 것은 어떨까 생각해봤습니다. type Role = 'admin' | 'user' | 'guest'
const getPolicyByRole = (policy: Record<Role, string[]>, role: Role) => {
return policy[role]
}
const policy = getPolicyByRole({
admin: ['create', 'read', 'update', 'delete'],
user: ['read'],
guest: ['read']
}, 'admin')함수의 형태는 이런 식으로 역할별 권한을 boolean이 아닌 string array로 정의해보는 것도 괜찮을 것 같아요. 본문의 맥락보다는 조금 동떨어진 의견이 아닐까 걱정됩나다만 누군가에게는 아이디어가 될 것 같아서 남겨봅니다^^ |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
시점 이동 줄이기 | Frontend Fundamentals
변경하기 쉬운 프론트엔드 코드를 위한 지침서
https://frontend-fundamentals.com/code/examples/user-policy.html
Beta Was this translation helpful? Give feedback.
All reactions