React 组件设计问题

这是个认证页面的组件,包装了React-routerRoute,现在的问题是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}
                            }}
                        />
                    )
                )}
            />
        )
    }
}
阅读 2k
1 个回答

加一个状态,没执行完就 render 一个 loading 页面

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题