【发布时间】:2018-05-24 01:49:28
【问题描述】:
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)
【问题讨论】:
-
这是您的实际代码吗?
-
@devserkan是的,部分代码。
-
为什么不直接把isLoginSuccess传给PrivateRoute呢?
标签: reactjs redux react-router