I am using the react router and semantic-ui sidebar. When the sidebar is toggled between visible and invisible, the router triggers its component (OilBarrelComponent
) to be recreated (rather than just 'pushed'). This seems unnecessary and has side effects that i don't want. Is there something wrong with my code that causes the OilBarrelContainer
component to be recreated just because I toggle the sidebar?
import {BrowserRouter as Router, Route, Link, Switch} from 'react-router-dom';
import {Sidebar, Segment, Button, Menu, Icon} from 'semantic-ui-react'
toggleSidebarVisibility = () => this.setState({ sidebarVisible: !this.state.sidebarVisible })
render() {
const { sidebarVisible } = this.state
return (
<Router history={history}>
<div>
<Sidebar.Pushable className="phsidebar" as={Segment}>
<Sidebar as={Menu} animation='push' width='thin' visible={sidebarVisible} icon='labeled' vertical inverted>
<Menu.Item className="sidebaritem" as={Link} to='/oilbarrel'>
Gauge
</Menu.Item>
</Sidebar>
<Sidebar.Pusher>
<div>
<MessagesContainer/>
<Switch>
<Route exact path="/" component={() => (<Home />)}/>
<Route exact path="/oilbarrel" component={() => (<OilBarrelContainer timer={true} topMargin={0} width={300} height={400} labelText={"Diesel"}/>)}/>
</Switch>
</div>
</Sidebar.Pusher>
</Sidebar.Pushable>
</div>
</Router>
)};
I suspect it's that your <Route>
's component
props are functions rather than just a reference to the component classes.
I.e. instead of
component={() => (<Home />)}
I believe it should be
component={Home}
I believe the former way re-renders a completely new component on every render, so there is no way for React to assert that a re-render is unnecessary.
来源:https://stackoverflow.com/questions/45066891/semantic-ui-sidebar-pusher-causing-react-router-to-rerender-its-component