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)
最佳答案
你可以这样做:
1.初始化isAuthenticated为null
2.in render return 使用私有(private)组件的条件渲染
const userAuth = {
isAuthenticated: null
}
在应用程序渲染中返回:
return (
<Router>
<div>
<Route path="/public" component={Public} />
{(userAuth.isAuthenticated!==null)?<PrivateRoute path="/private"
component={Private} />:null}
</div>
</Router>
);
关于reactjs - redux(用户认证)更新后React渲染私有(private)路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50499768/