在App.js中,我将状态和函数作为道具传递给Header.js,SideDrawer.js和Footer.js。每当App.js的状态发生变化时(即,当我单击Header.js上的链接时),Home.js都会重新渲染(我没有将任何内容传递给Home.js),这正常吗?如何防止Home.js重新呈现?
我曾尝试将Home Component(它是一个类组件)更改为PureComponent,但是当App的状态更改时,它仍然会重新呈现。
App.js
class App extends React.Component {
state = {
sideDrawerOpen: false,
subMenuOpen: false,
modalOpen: false
};
componentDidMount() {
store.dispatch(loadUser());
}
sideDrawerOpenHandler = () => {
this.setState(prevState => {
return { sideDrawerOpen: !prevState.sideDrawerOpen };
});
};
sideDrawerCloseHandler = () => {
this.setState({
sideDrawerOpen: false
});
};
subMenuOpenHandler = () => {
this.setState(
prevState => {
return { subMenuOpen: !prevState.subMenuOpen };
},
() => {
document.addEventListener("click", this.subMenuCloseHandler);
}
);
};
subMenuCloseHandler = () => {
this.setState(
{
subMenuOpen: false
},
() => {
document.removeEventListener("click", this.subMenuCloseHandler);
}
);
};
modalOpenHandler = () => {
this.setState(prevState => {
return { modalOpen: !prevState.modalOpen };
});
};
modalCloseHandler = () => {
this.setState({
modalOpen: false
});
};
render() {
let backDrop;
if (this.state.sideDrawerOpen || this.state.modalOpen) {
backDrop = (
<Backdrop
sideDrawerCloseHandler={this.sideDrawerCloseHandler}
subMenuCloseHandler={this.subMenuCloseHandler}
modalCloseHandler={this.modalCloseHandler}
/>
);
}
return (
<Provider store={store}>
<AlertProvider template={AlertTemplate} {...alertOptions}>
<Router>
<Header
sideDrawerOpenHandler={this.sideDrawerOpenHandler}
subMenuOpenHandler={this.subMenuOpenHandler}
subMenuOpen={this.state.subMenuOpen}
// subMenuCloseHandler={this.subMenuCloseHandler}
/>
<Alerts />
{this.state.modalOpen && (
<Trivia modalCloseHandler={this.modalCloseHandler} />
)}
<SideDrawer
sideDrawerOpen={this.state.sideDrawerOpen}
sideDrawerCloseHandler={this.sideDrawerCloseHandler}
subMenuOpenHandler={this.subMenuOpenHandler}
subMenuOpen={this.state.subMenuOpen}
subMenuCloseHandler={this.subMenuCloseHandler}
/>
{backDrop}
<Footer
modalOpenHandler={this.modalOpenHandler}
subMenuCloseHandler={this.subMenuCloseHandler}
/>
<main>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/roster/lakers" component={Lakers} />
<Route path="/roster/celtics" component={Celtics} />
<Route path="/roster/rockets" component={Rockets} />
<Route path="/roster/raptors" component={Raptors} />
<Route path="/roster/clippers" component={Clippers} />
<Route path="/roster/bucks" component={Bucks} />
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />
</Switch>
</main>
</Router>
</AlertProvider>
</Provider>
);
}
}
答案 0 :(得分:1)
重新渲染父视图时,所有可见的子视图也要渲染。您可以将home组件包装在React.memo中(如果它是功能组件),或者使用shouldComponentUpdate生命周期方法(如果是类)。这样可以防止不必要的重新渲染。