MST

星途 面试题库

面试题:React 条件渲染中如何处理复杂逻辑及性能优化

假设你在开发一个电商产品列表页面,根据产品的不同属性(如库存状态、是否新品、是否促销等)来进行复杂的条件渲染展示不同的样式和操作按钮。请描述如何设计条件渲染逻辑以保证代码的可读性与可维护性,同时说明如何进行性能优化,避免不必要的重新渲染。
46.5万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试

设计条件渲染逻辑以保证代码可读性与可维护性

  1. 使用函数封装条件逻辑:将每个条件判断逻辑封装成单独的函数,例如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;
}
  1. 使用对象映射:将不同条件组合对应的样式和操作按钮映射到一个对象中。例如:
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']
    },
    // 其他条件组合...
};
  1. 在渲染函数中根据条件获取配置:在渲染函数中,根据产品的实际条件组合,从映射对象中获取相应的样式和按钮配置。
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>
    );
}

性能优化避免不必要的重新渲染

  1. 使用React.memo:在React中,如果是函数组件,使用React.memo包裹组件。React.memo会对组件的props进行浅比较,如果props没有变化,组件不会重新渲染。
const ProductItem = React.memo(({ product }) => {
    // 渲染逻辑
});
  1. shouldComponentUpdate:如果是类组件,重写shouldComponentUpdate方法,手动比较当前和下一个props或state,只有在真正需要更新时才返回true
class ProductItem extends React.Component {
    shouldComponentUpdate(nextProps, nextState) {
        // 比较产品属性,例如只在产品信息变化时更新
        return nextProps.product.id!== this.props.product.id;
    }
    render() {
        // 渲染逻辑
    }
}
  1. 减少不必要的计算:在条件判断函数中,避免进行复杂且不必要的计算。例如,如果某个条件在一定时间内不会变化,可以将计算结果缓存起来,而不是每次渲染都重新计算。在上述isNew函数中,如果product.releaseDate不会频繁变化,可以将oneMonthAgo缓存起来。