react.js - React 组件设计问题

查看:101
本文介绍了react.js - 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}
                            }}
                        />
                    )
                )}
            />
        )
    }
}

解决方案

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

这篇关于react.js - React 组件设计问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆