gpt4 book ai didi

reactjs - 在 .map 循环内 react 不必要的重新渲染

转载 作者:行者123 更新时间:2023-12-03 14:30:21 33 4
gpt4 key购买 nike

我尝试在循环重新渲染内实现飞机座位图和我的座位组件,但我不明白为什么。

有代码:

export interface Props {
passengers: PassengerState[];
row: RowWithParts;
nextRow: RowWithParts;
rowIndex: number;
lastRow: number;
onSelect: (seat: SeatType) => void;
highlightedService: string; // <- Seats rerenders when i change this prop, I'm try to avoid this
setHighlightedService: (serviceId: string) => void;
passengerId: string;
segmentId: string;
}

const Row: React.FunctionComponent<Props> = React.memo(({ row, ...props }) => {

return (
<React.Fragment>
{props.rowIndex === 0 && (
<div className={cn(theme.row, theme.row_serviceClass)}>
{t(`${firstSeatService ? firstSeatService.serviceClass : 'Economy'} class`)}
</div>
)}

{!isLastRow && row.exitRow && <ExitRow />}
<div
className={cn(theme.row, {
[theme.row_otherClass]: props.rowIndex === 0,
[theme.row_nextRowHasOtherClass]: nextRowHasOtherServiceClass(row, props.nextRow)
})}
with-wings={row.wing ? 'true' : 'false'}
>
{row &&
row.parts &&
row.parts.map((part, partIndex) => {
// omit some logic here

return (
<div
key={partIndex}
onMouseEnter={() => {
// returns null for free seats and service for paid
// in other cases like aisles returns boolean
props.setHighlightedService(currentPartService) <-- change highlightedService prop here;
}}
onMouseLeave={() => props.setHighlightedService('')}
>
<div
className={cn(theme.row__seatWrapper)} // <-- here is we highlight sibling div, I'm omit some code here
/>

{part.map((seat, seatIndex) => {
// some Seat logic ( calculate availability etc. )


return (
<Seat // <-- React.memo ( this component doesn't need to rerender when highlightedService changes)
key={seatIndex}
seat={seat}
isOccupied={isOccupied}
isAvailable={isAvailable}
occupiedBy={occupiedBy}
isOccupiedByOtherPassenger={isOccupiedByOtherPassenger}
onSelect={props.onSelect}
/>
);
})}
</div>
);
})}
</div>
{isLastRow && row.exitRow && <ExitRow />}
</React.Fragment>
);
});

export default Row;

据我所知,React 应该仅使用 row__seatWrapper 类重新渲染 Row 和 div,但是,我看到 Seat 组件也重新渲染,你能解释一下我错过了什么吗?

我是否需要向内存的 Seat 组件添加自定义 prev/nextProps 比较功能?

更新

(prevProps, nextProps) => { // <-- propsAreEqual callback of Seat.tsx
console.log(prevProps === nextProps); // <-- false ???
for (const [prop] of Object.entries(prevProps)) {
if (prevProps[prop] !== nextProps[prop]) {
console.log(prop); // <-- doesn't log anything
}
}
}

最佳答案

当 ThemeProvider 更改时,似乎会发生不必要的重新渲染

export const ThemeProvider: React.FC<ThemeProviderProps> = React.memo(({ value, children }) => {
const theme: EngineTheme = useContext(ThemeContext);

return <ThemeContext.Provider value={mergeCSS(theme, value)}>{children}</ThemeContext.Provider>;
});

因为 Seat.tsx 从该上下文中获取其主题:(

关于reactjs - 在 .map 循环内 react 不必要的重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59156172/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com