Server-Side Auth Flow with React Router

爱⌒轻易说出口 提交于 2019-12-04 11:47:58

You could use context, e.g:

import React, { Component, PropTypes, Children } from 'react'

class Provider extends Component {

    static childContextTypes = {
        isAuthed: PropTypes.bool
    }

    constructor(props) {
        super(props);
        this.initialData = isClient ? window.__initialData__ : props.initialData;
    }

    getChildContext() {
        return {
            isAuthed: this.initialData.isAuthed
        };
    }

    render() {
        let { children } = this.props;
        return Children.only(children);
    }
}

And wrap:

// The server creates this object:
const initialData = {
    isAuthed: true
};

if (IS_CLIENT) {
    ReactDOM.render(
        <Provider>
            <Router history={createHistory()}>{Routes}</Router>
        </Provider>,
        document.getElementById('app')
    );
}

if (IS_SERVER) {
    // Using renderToStaticMarkup/renderToString etc on:
    <Provider initialData={initialData}> 
        <RoutingContext {...renderProps} />
    </Provider>
}

You can then access it on the server or client from any component:

import React, { Component, PropTypes } from 'react'

class SomeComponent extends Component {

    static contextTypes = {
        isAuthed: PropTypes.bool
    }

    constructor(props, context) {
        super(props, context);

        console.log(context.isAuthed); // this.context outside ctor
    }
}

Simple client check something like typeof document !== 'undefined'

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!