【发布时间】:2019-09-10 04:35:12
【问题描述】:
我在后端有 React 和 Node.js 以及 passport.js,它实现了我的应用程序身份验证。我的 react 调用我的后端并通过 action reducer 获取授权用户。一切正常,但路线守卫有问题。如果用户未登录,这就是我保护路由的方式
如果(!this.props.auth)返回
问题是当用户登录时,如果页面被刷新,上面的代码执行速度比mapStateToProps返回授权用户和loginIn用户重定向到索引页面要快。这是糟糕的用户体验。请帮助我如何解决此问题,我将不胜感激帮助和建议。
我认为我需要做的是确保在渲染 DOM 之前先更新商店,但我不知道该怎么做。
这里是仪表板
class Dashboard extends Component {
render() {
if(!this.props.auth) return <Redirect to='/' />
if (!this.props.auth.googleUsername) {
return <div className='container'> Loading ... </div>;
} else {
return (
<div className='container' style={{ margin: '10px 10px' }}>
{this.props.auth.googleUsername}
</div>
);
}
function mapStateToProps({auth}) {
return {auth};
}
export default connect(mapStateToProps)(Dashboard);
这里是 App.js
import { connect } from 'react-redux';
import { fetchUser } from './store/actions/index';
import Home from './components/layout/Home';
import Dashboard from './components/layout/Dashboard';
class App extends Component {
componentDidMount() {
this.props.fetchUser();
}
render() {
return (
<div>
<BrowserRouter>
<div>
<Header />
<Switch>
<Route exact path='/' component={Home} />
<Route path='/dashboard' component={Dashboard} />
</Switch>
</div>
</BrowserRouter>
</div>
);
}
}
export default connect(null,{ fetchUser })(App)
动作减速器
import axios from 'axios';
import { FETCH_USER } from './types';
export const fetchUser = () => async dispatch => {
const res = await axios.get('/api/current_user');
dispatch({ type: FETCH_USER, payload: res.data });
};
授权减少器
import { FETCH_USER } from '../actions/types';
export default function(state = false, action) {
switch (action.type) {
case FETCH_USER:
return action.payload;
default:
return state;
}
}
【问题讨论】:
标签: node.js reactjs express react-redux passport.js