这是个认证页面的组件,包装了React-router
的Route
,现在的问题是render
的时候,handleSignIn()
函数还没执行完,请问要怎么设计这个组件呢?
class AuthRoute extends Component {
constructor(props) {
super(props);
this.state = {
isAuthenticated: false
}
this.urls = {
signIn : 'http://xxxxxx:8080/bridge/login',
signOut: 'http://xxxxxx:8080/bridge/logout'
}
}
handleSignIn() {
axios.post(this.urls.signIn, {
username: 'admin',
password: '123456'
})
.then(response => {
console.log(1)
this.setState({isAuthenticated: true});
})
.catch(error => {
console.log(2)
this.setState({isAuthenticated: false});
});
}
handleSignOut() {
axios.post(this.urls.signOut)
.then(response => {console.log(response)})
.catch(error => {console.log(error)});
}
componentWillMount() {
this.handleSignIn();
}
render() {
const {
other
} = this.props;
return (
<Route
{...other}
render={props => (
this.state.isAuthenticated ? (
this.props.component
// <Component {...props} />
) : (
<Redirect
to={{
pathname: '/signin',
state: {from: props.location}
}}
/>
)
)}
/>
)
}
}
加一个状态,没执行完就 render 一个 loading 页面