-
Notifications
You must be signed in to change notification settings - Fork 4
Open
Description
每个组件控制状态尽量少,不要将所有状态维护在一个组件
Context 需要读写分离处理
优先使用 ahooks 等社区优秀 Hooks 库提供的方法
合理使用 useEffect
- 如果是用户主动触发的逻辑,写到事件函数里面
- 如果是渲染之后(displayed)触发的逻辑,写到 useEffect 里面
合理使用 useCallback/useMemo 能不用就不用
函数组件都要命名名称,不要使用匿名函数
Bad:
export default function() {}Good:
export default function Component() {}函数组件的入参尽量使用结构的形式
function Component({ title, value }) {
...
}更新多个状态,请合理抽象到一个对象。或者考虑使用 useReducer
Bad code:
const [count, setCount] = useState(0);
const [name, setName] = useState("");
const onClick = () => {
setTimeout(() => {
setName("John");
setCount(count + 1);
}, 1000);
};Good code:
const [state, setState] = useState({
count: 0,
name: "",
});
const onClick = () => {
setTimeout(() => {
setState((prevState) => ({
...prevState,
name: "John",
count: prevState.count + 1,
}));
}, 1000);
};不要在 JSX 里面写函数
Bad code:
return (
<div>
<button
onClick={() => {
setCount(1);
// ...
}}
>
Click
</button>
</div>
);Good code:
const onClick = useCallback(() => {
setCount(1);
// ...
}, [deps]);
return (
<div>
<button onClick={onClick}>Click</button>
</div>
);使用 object(Map) 替代 switch
Bad code:
switch (props.type) {
case "ADMIN":
return <Admin />;
case "USER":
return <User />;
default:
return <NotFound />;
}Good code:
const componentMap = {
ADMIN: Admin,
USER: User,
NOT_FOUND: NotFound,
};
const Component = componentMap[props.type];
return <Component />;Better code:
const componentMap = {
ADMIN: React.lazy(() => import("../components/Admin")),
USER: React.lazy(() => import("../components/User")),
NOT_FOUND: React.lazy(() => import("../components/NotFound")),
};
const Component = componentMap[props.type];
return <Component />;布尔类型,简短处理
Bad code:
return <button disabled={true}>Submit</button>;Good code:
return <button disabled>Submit</button>;如果没有子元素,就自闭处理
Bad code:
return <Component></Component>;Good code:
return <Component />;参考文档:
Metadata
Metadata
Assignees
Labels
No labels