[英]React-router - component reloads on parent component state change?
在我的React應用程序中,我有一個取自material-ui的demo的ResponsiveDrawer組件。 它基本上只是一個React組件,它呈現一個帶有菜單項列表,標題欄和內容框架的抽屜。
它的狀態為mobileOpen
state = {
mobileOpen: false
};
當用戶單擊漢堡包圖標時,它會更改
handleDrawerToggle = () => {
this.setState({ mobileOpen: !this.state.mobileOpen });
};
(...)
<Drawer type="temporary" anchor="left" open={this.state.mobileOpen} classes={{paper: classes.drawerPaper}} onRequestClose={this.handleDrawerToggle} ModalProps={{keepMounted: true // Better open performance on mobile.}}>
<div>
<div className={classes.drawerHeader} />
<Divider />
<MenuList onRequestClose={this.handleDrawerToggle} />
</div>
我還在ResponsiveDrawer的內容內設置了一些路由:
<main className={classes.content}>
<div className={classes.contentWrapper}>
<Switch>
<Route
exact
path="/currencies"
component={CurrenciesComponent}
/>
<Route
exact
path="/"
component={ProfileComponent}
/>
<Route component={NotFoundComponent} />
</Switch>
</div>
</main>
路由中的CurrenciesComponent定義如下:
const CurrenciesComponent = () => (
<Currencies isSignedIn={this.isSignedIn} />
);
當我單擊漢堡包圖標時,ResponsiveDrawer的狀態發生變化,但是CurrenciesComponent也被重新加載(我在那里有一個API調用,該調用需要幾秒鍾才能完成,所以我想避免這種情況)。
如果我按照以下方式定義路線(不將道具傳遞給Currencies組件),則不會發生:
<Route exact path="/currencies" component={Currencies} />
那么在指定路線時如何避免重新渲染並同時為貨幣提供道具?
我通過使用render
而不是component
prop來解決此問題:
<Route exact path="/currencies" render={CurrenciesComponent}/>
您可以告訴組件是否應該更新。
作為React生命周期的一部分,每個組件都有方法shouldComponentUpdate
,該方法在每次收到更新信號時都會運行。 從此函數返回true將指示組件進行更新,而false將指示其不進行更新。
由於您要做的只是要求它不渲染道具是否相同,因此您可以使用PureComponent而不是Component。 PureComponent實現了shouldComponentUpdate
,除非shouldComponentUpdate
或狀態發生了變化,否則不會更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.