设计条件渲染逻辑以保证代码可读性与可维护性
- 使用函数封装条件逻辑:将每个条件判断逻辑封装成单独的函数,例如
isInStock(product)
判断产品是否有库存,isNew(product)
判断是否为新品,isOnSale(product)
判断是否促销。这样在渲染逻辑中,调用这些函数可以使代码更清晰,也便于修改和扩展。
function isInStock(product) {
return product.stock > 0;
}
function isNew(product) {
// 假设新品是上架时间在最近一个月内
const oneMonthAgo = new Date();
oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);
return new Date(product.releaseDate) > oneMonthAgo;
}
function isOnSale(product) {
return product.discount > 0;
}
- 使用对象映射:将不同条件组合对应的样式和操作按钮映射到一个对象中。例如:
const renderConfig = {
inStockNewOnSale: {
style: 'in - stock - new - on - sale - style',
buttons: ['add to cart', 'buy now']
},
inStockNew: {
style: 'in - stock - new - style',
buttons: ['add to cart']
},
// 其他条件组合...
};
- 在渲染函数中根据条件获取配置:在渲染函数中,根据产品的实际条件组合,从映射对象中获取相应的样式和按钮配置。
function renderProduct(product) {
let key = '';
if (isInStock(product)) {
key += 'inStock';
}
if (isNew(product)) {
key += 'New';
}
if (isOnSale(product)) {
key += 'OnSale';
}
const config = renderConfig[key] || renderConfig.default;
return (
<div className={config.style}>
{/* 产品信息 */}
{config.buttons.map((button, index) => (
<button key={index}>{button}</button>
))}
</div>
);
}
性能优化避免不必要的重新渲染
- 使用React.memo:在React中,如果是函数组件,使用
React.memo
包裹组件。React.memo
会对组件的props进行浅比较,如果props没有变化,组件不会重新渲染。
const ProductItem = React.memo(({ product }) => {
// 渲染逻辑
});
- shouldComponentUpdate:如果是类组件,重写
shouldComponentUpdate
方法,手动比较当前和下一个props或state,只有在真正需要更新时才返回true
。
class ProductItem extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
// 比较产品属性,例如只在产品信息变化时更新
return nextProps.product.id!== this.props.product.id;
}
render() {
// 渲染逻辑
}
}
- 减少不必要的计算:在条件判断函数中,避免进行复杂且不必要的计算。例如,如果某个条件在一定时间内不会变化,可以将计算结果缓存起来,而不是每次渲染都重新计算。在上述
isNew
函数中,如果product.releaseDate
不会频繁变化,可以将oneMonthAgo
缓存起来。