简体   繁体   中英

React-router - component reloads on parent component state change?

In my React app, I have a ResponsiveDrawer component taken from material-ui's demo . It's basically just a React component which renders a drawer with a list of menu items, a title bar and content frame.

It has mobileOpen in its state

state = {
    mobileOpen: false
};

which changes when user clicks the hamburger icon

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>

I also have set up some routes inside the content of the 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 from the route is defined as follows:

const CurrenciesComponent = () => (
        <Currencies isSignedIn={this.isSignedIn} />
    );

When I click the hamburger icon, the state of ResponsiveDrawer changes, however the CurrenciesComponent is also reloaded (I have an API call there which takes a few seconds to complete so I would like to avoid this).

If I define my route as follows (without passing the props to Currencies component), this doesn't happen:

<Route exact path="/currencies" component={Currencies} />

So how do I avoid the re-render and provide props to Currencies at the same time when specifying the route?

我通过使用render而不是component prop来解决此问题:

<Route exact path="/currencies" render={CurrenciesComponent}/>

You can tell your component if it should update.

As part of React's lifecycle, each component has the method shouldComponentUpdate that gets run each time it gets a signal to update. Returning true from this function will tell the component to update and false will tell it not to.

Since all you're doing is asking it not to render if the props remain the same, you may be able to use PureComponent instead of Component. PureComponent implements shouldComponentUpdate and doesn't update unless props or state has changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM