PrivateRoute在Redux从服务器获取当前用户数据之前进行渲染。解决此问题的最佳方法是什么?
该组件如下所示。 userAuth.isAuthenticated
最终更新为true
,但在更新之前首先呈现<Redirect to="/login" />
。
const userAuth = {
isAuthenticated: false
}
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
// PROBLEM: this renders before Redux gets user authentication data from the server
userAuth.isAuthenticated ? <Component {...props} /> : <Redirect to="/login" />
)}/>
)
class App extends Component {
componentDidMount() {
// Get current user data when user refresh the browser
// This sets isLoginSuccess: true is current user is logged-in in Redux store
this.props.getCurrentUserSession();
}
render() {
// Show loading icon while fetching current user data
if(this.props.user.isFetchingCurrentUserSession){
return (<div><img src={squareLogo} className="logo-loading" alt="Loading icon" /></div>);
}
// Set current user authentication status
userAuth.isAuthenticated = this.props.user.isLoginSuccess
return (
<Router>
<div>
<Route path="/public" component={Public} />
<PrivateRoute path="/private" component={Private} />
</div>
</Router>
);
}
}
function mapStateToProps(state) {
return state
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
getCurrentUserSession
}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
答案 0 :(得分:2)
你可以这样做:
1.Intialize isAuthenticated为null
2.in渲染返回使用私有组件的条件渲染
const userAuth = {
isAuthenticated: null
}
in App render return:
return (
<Router>
<div>
<Route path="/public" component={Public} />
{(userAuth.isAuthenticated!==null)?<PrivateRoute path="/private"
component={Private} />:null}
</div>
</Router>
);