function PrivateRoute ({component: Component, authed, ...rest}) {
return (
<Route
{...rest}
render={(props) => authed === true
? <Component {...props} />
: <Redirect to={{pathname: '/login', state: {from: props.location}}}/>}
/>
)
}
我借用了前一个组件,我想保留一个像loggedIn这样的状态属性,然后在获取承诺之后更新这个组件状态,因为我不想像authed
任何地方一样存储布尔属性。另外我是 react 和 react-router (V4) 的新手,我练习了 3 周,提前谢谢!到目前为止我得到了这个:
class AuthRoute extends React.Component {
constructor(props){
super(props);
this.state = {checking: true, loggedIn:false};
}
componentDidMount(){
fetch('/sourcing/auth/loggedin',{credentials:'include', method:'POST'})
.then(res => res.json())
.then(user => {
console.log('user dans le fetch', user);
if(user !== null)
this.setState({loggedIn: true, checking: false});
})
}
render() {
const {component , ...rest} = this.props;
return(
!this.state.checking && this.state.loggedin
? <DefaultLayoutRoute {...rest} component={component} />
: <Redirect to='/login' />
);
}
}
主要问题是我在该组件卸载之后设置了状态,我想要一种正确的方法来等待获取而不发出同步请求