我建立了一个HOC,可在我的应用中的受保护路线上使用。它接收应该在路径上呈现的组件,检查用户是否已通过身份验证,然后呈现该组件是否经过身份验证。它可以工作,但是会导致该组件多次挂载/卸载(与调用app.js文件中的render函数的次数相同)。
来自我的app.js的路线
<Switch> <Route path='/groups/show/:id' component={ RequireAuth(Group) } /> <Route path='/groups/create' component={ RequireAuth(CreateGroup) } /> <Route path='/groups' component={ RequireAuth(GroupsMenu) } /> <Route path='/tutorials/:id' component={ Tutorial } /> <Route path='/tutorials' component={ TutorialMenu } /> <Route path='/ranked' component={ RankedPlay } /> <Route path='/casual' component={ CasualPlay } /> <Route path='/offline' component={ OfflinePlay } /> <Route path='/signup' component={ Signup } /> <Route path='/' component={ Menu } /> </Switch>
require_auth.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import { store } from '../../index'; import { AUTH_ERROR } from '../../actions'; import PropTypes from 'prop-types'; import Display from './display'; export default function(ComposedComponent) { class Authentication extends Component { static propTypes = { history: PropTypes.object.isRequired }; componentWillMount() { const { history } = this.props; const error = 'You must be logged in to do this. Please login'; if (!this.props.authenticated) { store.dispatch({ type: AUTH_ERROR, payload: error }); history.push('/'); } } componentWillUpdate(nextProps) { const { history } = this.props; const error = 'You must be logged in to do this. Please login'; if (!nextProps.authenticated) { store.dispatch({ type: AUTH_ERROR, payload: error }); history.push('/'); } } render() { return ( <Display if={ this.props.authenticated } > <ComposedComponent { ...this.props } /> </Display> ); } } function mapStateToProps(state) { return { authenticated: state.auth.authenticated }; } return withRouter(connect(mapStateToProps)(Authentication)); }
如果从任何一条路由中删除RequireAuth(),则在您击中该路由时,组件只会安装一次。但是添加它会导致组件在app.js render()每次启动时挂载。有什么办法可以设置此组件,使其仅安装一次?
通过调用RequireAuth(Component)render,您将Component在每个渲染调用中使用HOC 进行修饰,从而使每个渲染在每个渲染中都返回一个 新的 Component。
RequireAuth(Component)
Component
你应该装饰Group,CreateGroup并GroupsMenu用RequireAuth,出口之前。就像你用react- redux的connect。
Group
CreateGroup
GroupsMenu
RequireAuth
react- redux
connect