我们的应用程序当前使用React路由器和HOC在或系统中创建身份验证。我对编写没有额外身份验证层但对如何处理我编写的代码感到困惑的组件的测试很满意。我一直在寻找专门有关react-router身份验证的文档,并且卡住了。处理响应路由器中的HOC的最佳方法是什么?
index.js
const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(reducers);
const token = localStorage.getItem('token');
if (token) {
store.dispatch({ type: AUTH_USER });
}
ReactDOM.render(
<Provider store={store}>
<App id={token} />
</Provider>,
document.querySelector('.app')
);
App.js
function PrivateRoute({ component: Component, auth, ...rest }) {
return (
<Route
{...rest}
render={props =>
auth ? (<div><Component {...props} /></div>) : (
<Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)
}
/>
);
}
function PublicRoute({ component: Component, auth, ...rest }) {
return <Route {...rest} render={props => (!auth ? <Component {...props} /> : <Redirect to="/dashboard" />)} />;
}
class App extends Component {
static contextTypes = {
router: PropTypes.object,
};
render() {
return (
<Router history={history} >
<Switch>
<PublicRoute auth={this.props.auth} path="/login" exact component={Login} />
<PrivateRoute auth={this.props.auth} path="/dashboard" exact component={Dashboard} />
</Switch>
</Router>
);
}
}
function mapStateToProps(state) {
return {
auth: state.auth.authenticated,
};
}
export default connect(
mapStateToProps,
null
)(App);