Reactjs 为什么App.js中的状态更改会导致组件重新安装?
在App.js文件中,我正在执行路由(对于路由,我使用react-routesv4)。关于路线,还有侧边栏。侧边栏的原因我有一个控制侧边栏的状态。每当侧栏状态更改时,与当前路由连接的其他组件都将重新安装 例如,这里我有一个组件用户,每当侧栏状态改变时,它都会重新安装。在ComponentUser中,我使用useEffects钩子获取数据,所以每一个边栏状态的改变都会触发该钩子Reactjs 为什么App.js中的状态更改会导致组件重新安装?,reactjs,react-router,Reactjs,React Router,在App.js文件中,我正在执行路由(对于路由,我使用react-routesv4)。关于路线,还有侧边栏。侧边栏的原因我有一个控制侧边栏的状态。每当侧栏状态更改时,与当前路由连接的其他组件都将重新安装 例如,这里我有一个组件用户,每当侧栏状态改变时,它都会重新安装。在ComponentUser中,我使用useEffects钩子获取数据,所以每一个边栏状态的改变都会触发该钩子 const App = ({classes}) => { const [isDrawerOpen, se
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;
const-App=({classes})=>{
const[isDrawerOpen,setIsDrawerOpen]=useState(false);
常量handleDrawerToggle=()=>{
setIsDrawerOpen(!isDrawerOpen)
};
返回(
);
};
导出默认样式(样式)(应用程序);
常量授权=(allowedRoles)=>(WrappedComponent)=>{
const with authorization=(道具)=>{
const role=helpers.getRole();
如果(角色===null){
回来
}else if(allowedRoles.includes(role)){
回来
}否则{
返回您没有访问权限
}
};
授权退货;
};
出口默认授权;
不知道是什么导致了这种行为?这是因为每次渲染时都会对HoC进行评估。尝试:
const AuthorisedComponent = requireLogin(MyComponent); // instantiate hoc once
<Route path="/mycomponent" component={AuthorisedComponent} /> // use hoc
const authorized component=requireLogin(MyComponent);//实例化hoc一次
//使用hoc
这是真实的代码,或者您在某些路由中有Hoc?我有一个Hoc授权,它包装了需要渲染的每个组件,现在当您说我删除了它,它现在侧栏状态更改没有重新安装组件(我编辑了问题)它仍然重新安装组件。应该仍然是由于一些Hoc,您可以发布更新的代码吗?将const声明放在render之外是相关的