我在我制作的其他React应用中使用了相同的设置,对于我一生,我不知道为什么它不再起作用。我注意到这是react-router的更高版本,但它与我阅读的内容相比应该没有重大变化。
当我尝试转到/ tweets路由时,出现错误
TypeError: Cannot set property 'props' of undefined
如果我转到/ tweets2路由,则会将我转到404未找到路由。
所有未经身份验证的路由似乎都可以正常工作。
非常感谢您的帮助。
import React from 'react';
import { BrowserRouter, Route, Switch} from 'react-router-dom'
import { Redirect } from 'react-router';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import Login from './views/login/LoginPage.js';
import Logout from './views/logout/LogoutPage';
import TweetList from './views/tweets/tweetList';
import NotFound from './views/notfound/NotFoundPage';
import './App.css';
function loggedIn() {
console.log("loggedIn() was called")
let token = localStorage.getItem('token');
let timestamp = localStorage.getItem('timestamp');
let potentialExp = timestamp/1000 + 7200; // 2 hours after token was created in seconds
/*Checks if there's a token in local storage and if the timestamp is older than 2 hours.
These are simply quick front end checks. All auth is really done server side.
*/
if( token != null && timestamp != null && potentialExp > new Date().getTime()/1000){
console.log("the user met logged in condition")
return true;
}else{
console.log(" the user did NOT meet logged in condition")
return false
}
}
const theme = createMuiTheme({
palette: {
primary: {
light: '#8551fd',
main: '#814ff8',
dark: '#051550',
contrastText: '#fff',
},
secondary: {
light: '#f2f7fe',
main: '#B0BEC5',
dark: '#B0BEC5',
contrastText: '#fff',
},
}
});
const PrimaryLayout = () => (
<div className="primary-layout">
<main>
<Switch>
<Route path="/" exact component={Login} />
<Route path="/tweets" exact render={(passedProps) => (
!loggedIn() ? (
<Redirect to={`/login`}/>
) : (
<TweetList {...this.props = passedProps}/>
)
)}/>
<Route path="/tweets2" exact render={(props) => (
!loggedIn() ? (
<Redirect to={`/login`}/>
) : (
<TweetList {...props}/>
)
)}/>
<Route path="/logout" exact component={Logout} />
<Route exact component={NotFound} />
</Switch>
</main>
</div>
)
const App = () => (
<BrowserRouter>
<MuiThemeProvider theme={theme}>
<PrimaryLayout />
</MuiThemeProvider>
</BrowserRouter>
)
export default App;