基于 ajax 请求呈现重定向组件



我有一个家庭路由"/",每当用户转到该路由时,如果他经过身份验证,我想将他发送到他的页面,或者如果他未通过身份验证,则将其发送到"/login"路由。为了将用户发送到他的页面,我向服务器发出请求,获取他的 ID 并根据我从服务器获得的 id 将他重定向到路由。但是,对于如何在我的 Home 组件中正确实现该逻辑,我有点困惑。根据 ajax 请求的结果呈现重定向组件的最佳方法是什么?

class Home extends React.Component {
async componentDidMount() {
const response = await Api.getUserId();
const id = response.data._id;
}  
render() {
if(this.props.userStatus.authenticated) {
return <Redirect to={{
pathname: `/${id}`,
state: { from: this.props.location }
}}/>
}
return <Redirect to={{
pathname: '/login',
state: { from: this.props.location }
}}/>
}
}
export default connectComponent(['userStatus'], Home);

你可以这样做: 创建一个名为 PrivateRoute 的新组件:

import React from 'react'
import { Redirect, withRouter, Route } from 'react-router-dom'
import { isLogin } from '../actions/actions_rents'
import { connect } from 'react-redux'
const PrivateRoute = ({ component: Component, ...rest }) => {
return(
<Route {...rest} render={props => (
isAuthenticated ? (
<Component />
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
)
}

然后在您的应用程序中.js或者您有路由的地方,您可以调用 PrivateRoute 并将组件 Home 作为道具传递,在这种情况下:

<Switch>
<Route path="/login" component={Login}/>
<PrivateRoute path="/" component={IndexRents} />
</Switch>

另外,我建议您查看此示例: https://reacttraining.com/react-router/web/example/auth-workflow

fetch('//offline-news-api.herokuapp.com/stories')
.then(function (response) {
console.log(response);
const login = response.ok;
class Entry extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<Router>
<Switch>
<Route exact path="/login" component={Login}/>
<Route path="/" render={() => (
login ? (
<Common/>
) : (
<Redirect to="/login"/>
)
)}/>
</Switch>
</Router>
);
}
}
ReactDOM.render(<Entry/>, document.getElementById('root'));
})
.then(function (stories) {
});

最新更新