[英]React components wait for each others to render
My restaurant order application has two main part, the header
part (navigation bar) and the Menu content
.我的餐厅订单应用程序有两个主要部分, header
部分(导航栏)和Menu content
。 When I click a link
in the header
, the link
will be come active (its style change), and the Menu content
change.当我单击header
中的link
时,该link
将变为活动状态(其样式更改),并且Menu content
发生更改。 The link
is a controlled component. link
是受控组件。 However, I noticed React waits for the Menu
part then update both parts at the same time.但是,我注意到 React 会等待Menu
部分,然后同时更新这两个部分。 This is not my desired behavior because when the Menu
is big, the page stands still for a few seconds.这不是我想要的行为,因为当Menu
很大时,页面会静止几秒钟。 How can I fix this behavior?我该如何解决这种行为? I tried React.lazy
but it doesn't seem to work我试过React.lazy
但它似乎不起作用
export default function MainPage({ cartState }: MainPageType): JSX.Element {
const menuInfo: IPayload = useContext(MenuInfoContext);
const { currentCategoryCode } = useContext(MenuStateContext);
if (Object.keys(menuInfo).length === 0) return <Spinner />;
const TopOrMenuList = currentCategoryCode === "0" ? <Top /> : <MenuList />;
return (
<>
<Header />
{TopOrMenuList}
</>
);
}
The link component is as bellow链接组件如下
export const CategoryButton = React.memo(function CategoryButton({
categoryCode,
categoryName,
active,
}: CategoryButtonType) {
const dispatch = useContext(DispatchContext);
const handleClick = () => {
playSound("page");
dispatch({ type: "currentCategoryCode", payload: categoryCode });
};
const className: string = active ? "active" : "";
return (
<div
id={`category-btn-${categoryCode}`}
className={className}
onClick={handleClick}
>
{categoryName}
</div>
);
});
The Menu content
change by using key currentCategoryCode
to get its content from menuInfo
. Menu content
通过使用 key currentCategoryCode
更改以从menuInfo
获取其内容。 menuInfo
is passed to all components through useContext
. menuInfo
通过useContext
传递给所有组件。
EDIT: I tried moving the conditional render into the return statement like suggestions but it still doesn't help编辑:我尝试将条件渲染移动到返回语句中,如建议,但它仍然无济于事
export default function MainPage({ cartState }: MainPageType): JSX.Element {
const menuInfo: IPayload = useContext(MenuInfoContext);
const { currentCategoryCode } = useContext(MenuStateContext);
return (
<>
{Object.keys(menuInfo).length === 0 ? (
<Spinner />
) : (
<>
<Header />
{currentCategoryCode === "0" ? <Top /> : <MenuList />}
</>
)}
</>
);
}
use setTimeout
inside useEffect
to provide the data content for Menu
after a few miliseconds, render an empty content initially.在useEffect
中使用setTimeout
在几毫秒后为Menu
提供数据内容,最初渲染一个空内容。 React will then update the header
first然后 React 将首先更新header
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.