在重定向之前,您将如何等待componentDidMount / componentWillMount中的提取? ReactJs

时间:2017-07-21 14:32:09

标签: reactjs react-router higher-order-components

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这样的布尔属性。我也是新的反应和反应 - 路由器(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' />
        );
    }
}

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

1 个答案:

答案 0 :(得分: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' />
        }
    }
}