在路由之间浏览时,由于请求2页,我的react auth组件导致闪烁。例如:用户请求一个名为StaffMeetingsPage
的新组件,首先运行AuthenticateComponent
然后运行StaffMeetingsPage
。这对我造成了闪烁。有没有办法解决它,并使身份验证代码更可重用?
App.js
import React from 'react';
import HomePage from './home/HomePage';
import { BrowserRouter, Route } from 'react-router-dom';
import Login from "./home/Login";
import StaffMeetingsPage from "./StaffMeetings/StaffMeetingsPage";
import NotFound from "./NotFound";
import AuthenticateComponent from "./AuthenticateComponent";
const App = () => {
return (
<BrowserRouter >
<div>
<Route exact={true} path="/" component={HomePage}/>
<Route exact={true} path="/login" component={Login}/>
<AuthenticateComponent>
<Route exact={true} path="/meetings" component={StaffMeetingsPage}/>
</AuthenticateComponent>
</div>
</BrowserRouter>
);
}
export default App;
AuthenticateComponent.js
import React from 'react';
import { getJwt } from '../jwthelper.js';
import axios from 'axios';
import { withRouter } from 'react-router-dom';
class AuthenticateComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
user: undefined
}
}
componentDidMount() {
const jwt = getJwt();
if (!jwt) {
this.props.history.push('/login');
} else {
let axiosConfig = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'x-auth': jwt
}
};
axios.get('/auth/me', axiosConfig).then((user) => {
//Set users data to state
this.setState({user: user.data});
}).catch(res => {
localStorage.removeItem('tkn');
this.props.history.push('/login');
});
}
}
render() {
if (this.state.user === undefined) {
return <div>Loading user data...</div>;
} else {
return <div>{this.props.children}</div>;
}
};
};
export default withRouter(AuthenticateComponent);
StaffMeetingsPage.js
import React from 'react';
class StaffMeetingsPage extends React.Component {
componentDidMount() {
document.title = "Staff Meetings";
}
render() {
return(
<div>
No meetings found...
</div>
);
}
}
export default StaffMeetingsPage;
答案 0 :(得分:0)
尝试
return null
代替
<div>Loading user data...</div>