React 最佳实践和模式以减少代码 - 第 2 部分
我还有另一篇关于 React 最佳实践和减少代码量模式的文章。在开始编写自己的 React 代码之前,这篇文章值得一读。
React 最佳实践和模式以减少代码 - 第 1 部分
事不宜迟,让我们来看看一些减少代码的最佳实践和模式。我们从最常见的开始。
如果组件没有子道具,请使用自闭合标签。
错误代码:
return <Component></Component>;
好的代码:
return <Component />;
不要在 jsx 元素内编写函数。
错误代码:
return (
<div>
<button
onClick={() => {
setCount(1);
// ...
}}
>
Click
</button>
</div>
);
好的代码:
const onClick = useCallback(() => {
setCount(1);
// ...
}, [deps]);
return (
<div>
<button onClick={onClick}>Click</button>
</div>
);
如果必须同时更新多个状态,请使用对象状态。
避免连续多次调用 setState。这是一个常见错误,会导致大量不必要的重新渲染。最好只调用一次 setState。
错误代码:
const [count, setCount] = useState(0);
const [name, setName] = useState("");
const onClick = () => {
setTimeout(() => {
setName("John");
setCount(count + 1);
}, 1000);
};
好的代码:
const [state, setState] = useState({
count: 0,
name: "",
});
const onClick = () => {
setTimeout(() => {
setState((prevState) => ({
...prevState,
name: "John",
count: prevState.count + 1,
}));
}, 1000);
};
注意: React 18 添加了自动批处理,因此多个更新将由 React 本身处理。
使用 styled-components 来设置组件的样式。这是一种避免在 JSX 中编写 CSS 的好方法,也有助于避免为应用程序设置 CSS。
这完全是基于观点的。
错误代码:
return <div style={{ backgroundColor: "red" }}></div>;
好的代码:
const Container = styled.div`
background-color: ${({ theme }) => theme.colors.background};
padding: 1rem;
`;
更好的代码:
const getPrimaryColor = ({ theme }) => theme.colors.primary;
const getDefaultColor = ({ theme }) => theme.colors.secondary;
const Button = styled.button`
background-color: ${getPrimaryColor};
color: ${getDefaultColor};
`;
注意:创建函数从主题中获取颜色和其他样式,并将它们传递给样式组件。这也有助于减少代码量。
尽量避免使用基于类的组件,而改用功能组件。
错误代码:
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
this.onClick = this.onClick.bind(this);
}
onClick = () => {
this.setState({
count: this.state.count + 1,
});
};
render() {
return <button onClick>Click me</button>;
}
}
好的代码:
const Counter = () => {
const [count, setCount] = useState(0);
const onClick = () => setCount(count + 1);
return <button>Click me</button>;
};
注意:函数组件不仅减少了开发时间和代码量,还减少了生产环境的 bundle 大小。它能将 bundle 大小减少近 60%。
React.memo 避免不必要的重新渲染。
错误代码:
return (
<ui>
{items.map((item) => (
<Component>{item}</Component>
))}
</ui>
);
好的代码:
const MemoComponent = React.memo(Component);
return (
<ui>
{items.map((item) => (
<MemoComponent>{item}</MemoComponent>
))}
</ui>
);
注意:请React.memo()
明智使用,不要在组件经常使用 props 重新渲染的地方使用 memo。
使用 JSX ShortHand,尝试使用 JSX 简写来传递布尔变量。
错误代码:
return <button disabled={true}>Submit</button>;
好的代码:
return <button disabled>Submit</button>;
使用三元运算符代替 if-else 语句。
错误代码:
if (isLoading) {
return <div>Loading...</div>;
} else {
return <div>Data</div>;
}
好的代码:
return isLoading ? <div>Loading...</div> : <div>Data</div>;
使用 object(Map) 代替 switch 语句。我在上一篇关于 Reducer 的文章中已经提到过这一点。
错误代码:
switch (props.type) {
case "ADMIN":
return <Admin />;
case "USER":
return <User />;
default:
return <NotFound />;
}
好的代码:
const componentMap = {
ADMIN: Admin,
USER: User
};
const Component = componentMap[props.type] ?? NotFound;
return <Component />;
更好的代码:
const NotFound = React.lazy(() => import("../components/NotFound"));
const componentMap = {
ADMIN: React.lazy(() => import("../components/Admin")),
USER: React.lazy(() => import("../components/User")),
};
const Component = componentMap[props.type] ?? NotFound;
return <Component />;
使用对象解构而不是按名称将多个 props 传递给组件。
错误代码:
const { name, age, role } = props;
return (
<>
<Component name={name} age={age} role={role} />
</>
);
好的代码:
return (
<>
<Component {...props} />
</>
);
当您不将字符串传递给组件时,不需要花括号。
错误代码:
return <Component name={"John"} />;
好的代码:
return <Component name="John" />;
不要使用诸如 等反应元素道具className
作为style
组件自定义道具。
错误代码:
return (
<Component style="bordered">
);
好的代码:
return (
<Component variant="bordered">
);
使用片段代替 div、span 等 html 元素。
错误代码:
return (
<div>
<span>{props.name}</span>
<span>{props.age}</span>
</div>
);
好的代码:
return (
<>
<span>{props.name}</span>
<span>{props.age}</span>
</>
);
if
如果块返回某些内容,则不要使用 else 块。
错误代码:
if (props.name) {
return <div>{props.name}</div>;
} else {
return <div>No name</div>;
}
好的代码:
if (props.name) {
return <div>{props.name}</div>;
}
return <div>No name</div>;
当您不使用该属性时,请使用 React.fragment 代替 div、span 等 Html 元素key
。
错误代码:
return (
<container>
{list.map((item) => (
<div key={item.id}>
<SomeComponent />
<SomeAnotherComponent />
</div>
))}
</container>
);
好的代码:
return (
<>
{list.map((item) => (
<React.Fragment key={item.id}>
<SomeComponent />
<SomeAnotherComponent />
</React.Fragment>
))}
</>
);
感谢您的阅读😊
有任何问题或其他信息吗?请留言。
如果你还没有读过

如何使用 AbortController 取消 Javascript API 请求
Rahul Sharma ・ 2022年4月9日
#javascript #webdev #frontend #html
关注我
Youtube Github LinkedIn Medium Stackblitz Hashnode HackerNoon
文章来源:https://dev.to/devsmitra/react-best-practices-and-patterns-to-reduce-code-part-2-54f3