为什么App.js中的状态更改会导致组件重新安装?

时间:2019-07-08 14:53:23

标签: reactjs react-router

在App.js文件中,我正在路由(对于路由,我正在使用react-routesv4)。有了路线,也有侧边栏。侧边栏的原因我有控制该侧边栏的状态。每当侧边栏状态更改时,与当前路由连接的其他组件都会重新安装。

例如,在这里,我有组件User,它在每次侧栏状态更改时都重新安装。在组件User中,我正在使用useEffects挂钩获取数据,因此每个侧栏状态更改也会触发该挂钩。

const App = ({classes}) => {

    const [isDrawerOpen, setIsDrawerOpen] = useState(false);

    const handleDrawerToggle = () => {
        setIsDrawerOpen(!isDrawerOpen)
    };

    return (
        <BrowserRouter>

            <CssBaseline/>

            <Switch>

               <Route path={'/login'} component={Login}/>

               <Fragment>
                  <Sidebar isDrawerOpen={isDrawerOpen} toggleDrawer={handleDrawerToggle}/>
                  <main role="main" className={classes.content}>
                      <Switch>
                          <Route exact path='/' component={User(Dashboard)}/>
                          <Route path='/users' component={Admin(Users)}/>
                      </Switch>
                  </main>
              </Fragment>

          </Switch>

      </BrowserRouter>
   );
};

export default withStyles(styles)(App);

const Authorization = (allowedRoles) => (WrappedComponent) => {
 const WithAuthorization = (props) => {

     const role = helpers.getRole();

     if(role === null){
         return <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
     } else if (allowedRoles.includes(role)) {
         return <WrappedComponent {...props} />
     } else {
         return <Typography>You don't have access</Typography>
     }

   };

    return WithAuthorization;
};

export default Authorization;

不知道是什么原因导致了这种行为?

1 个答案:

答案 0 :(得分:1)

这是由于每个渲染都会评估HoC。试试:

const AuthorisedComponent = requireLogin(MyComponent); // instantiate hoc once

<Route path="/mycomponent" component={AuthorisedComponent} /> // use hoc