我试图将我的PrivateRoute功能分离到一个单独的javascript文件中,当我将该功能移到一个单独的文件中时,该页面呈现空白。当该函数在App.js中是本地的时,所有功能均按预期工作,当我未经过身份验证时尝试按“ /”时,我将根据需要重定向到“ / login”。我的代码如下:
PrivateRoute.js
import React from 'react'
import { BrowserRouter as Route, Redirect } from "react-router-dom"
const PrivateRoute = ({ component: Component, ...rest }) => {
let isAuthenticated = rest.isAuthenticated;
return (
<Route
{...rest}
render={props =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: "/login", state: { from: props.location }}}
/>
)
}
/>
);
}
export default PrivateRoute;
App.js
import React, { Component } from 'react'
import NavBar from './components/Navbar.js'
import { BrowserRouter as Router, Route, Redirect } from "react-router-dom"
import Login from './Login.js'
import { Auth } from "aws-amplify"
import CustomModal from './components/CustomModal.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import { fab } from '@fortawesome/free-brands-svg-icons'
import { faSpinner } from '@fortawesome/free-solid-svg-icons'
import NewQuestion from './NewQuestion.js'
import PrivateRoute from './PrivateRoute.js'
library.add(fab, faSpinner)
function Index() {
return <h2>Home</h2>;
}
class AppRouter extends Component {
constructor(props) {
super(props);
this.state = {
isAuthenticated: false,
isAuthenticating: true,
showModal: false
};
this.onCancelClick = this.onCancelClick.bind(this);
this.onConfirmClick = this.onConfirmClick.bind(this);
}
async componentDidMount() {
try {
await Auth.currentSession();
this.userHasAuthenticated(true);
} catch(e) {
if (e !== 'No current user') {
alert(e);
}
}
this.setState({ isAuthenticating: false });
}
userHasAuthenticated = authenticated => {
this.setState({ isAuthenticated: authenticated });
}
handleLogout = async event => {
this.setState({ showModal: true });
}
onCancelClick() {
this.setState({ showModal: false });
}
async onConfirmClick() {
await Auth.signOut();
this.setState({ showModal: false });
this.userHasAuthenticated(false);
}
render() {
let navBar = this.state.isAuthenticated ? <NavBar onLogout={this.handleLogout} /> : null;
let showModal = this.state.showModal;
let modal;
if (showModal) {
const modalProps = {
title: "Log out",
message: "Are you sure you wish to Log Out?",
cancelButtonText: "Cancel",
confirmButtonText: "Log Out",
onCancelClick: this.onCancelClick,
onConfirmClick: this.onConfirmClick
}
modal = <CustomModal show={showModal} modalProps={modalProps} />
}
return (
!this.state.isAuthenticating &&
<Router>
<div>
{navBar}
<div className="container">
<Route path="/login" render={(props) => <Login {...props} userHasAuthenticated={this.userHasAuthenticated} />} />
<PrivateRoute path="/" exact component={Index} isAuthenticated={this.state.isAuthenticated} />
<PrivateRoute path="/users" component={NewQuestion} isAuthenticated={this.state.isAuthenticated} />
</div>
{ modal }
</div>
</Router>
);
}
}
export default AppRouter;