0
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' />
        );
    }
}

主要问题是我在该组件卸载之后设置了状态,我想要一种正确的方法来等待获取而不发出同步请求

4

1 回答 1

0

我通过为渲染方法添加另一个测试来解决我的问题,我忘记发布我的答案:

class AuthenticatedRoute extends React.Component {

    constructor(props)
    {
        super(props);
        this.state = {checking: true, loggedIn:false};
        this.validate = this.validate.bind(this);
    }

    validate = (user, loggedIn , checking) => {
        storeUser(user);
        this.setState({loggedIn: loggedIn, checking: checking});
        if(loggedIn) console.log("loggedIn");
    } 

    componentWillMount(){
        fetch('/sourcing/auth/loggedin',{credentials:'include', method:'POST'})
            .then(res => res.json())
            .then(user => {
                if(user){
                    this.validate(user, true ,false);
                }
                else
                    this.validate(null, false, false);
            })
            .catch(() => this.validate(null, false, false))
    }

    render() {
        const {component:Component , ...rest} = this.props;

        if(this.state.checking){
            return <DefaultLayoutRoute {...rest} component={() => <div>Loading...</div> } />
        }
        if(this.state.loggedIn){
           return <DefaultLayoutRoute {...rest} loggedIn={this.state.loggedIn} component={Component} />
        }
        if(!this.state.checking && !this.state.loggedIn){
            return <Redirect to='/login' />
        }
    }
}
于 2017-08-25T12:54:38.473 回答