让ReactJS mixins需要一个外部模块

时间:2015-09-02 02:48:53

标签: javascript reactjs mixins

我知道我们应该避免使用mixins,但让我们在这种情况下使用它。

我将一些登录/注销功能定义为mixins模块,我需要在许多组件中使用它。

var loginStore = require('../../stores/LoginStore'); // this is the problem ?
var AuthMixins = {
    statics: {
        willTransitionTo(transition) {
            console.log(loginStore.id);
            if (!loginStore.isLoggedIn()) {
                transition.redirect('login');
            }
        }
    },
    _getLoginState() {
        return {
            userLoggedIn: loginStore.isLoggedIn()
        };
    },
    componentDidMount() {
        this.changeListener = this._onChange;
        loginStore.addChangeListener(this.changeListener);
    },
    _onChange() {
        this.setState(this._getLoginState());
    },
    getInitialState() {
        return {
            userLoggedIn: this._getLoginState()
        };
    },
    componentWillUnmount: function() {
        loginStore.removeChangeListener(this.changeListener);
    }
};
module.exports = AuthMixins;

LoginStore.js:

var AppDispatcher = require('../dispatchers/AppDispatcher');
var EventEmitter = require('events').EventEmitter;
var LoginStore = (function() {
    var _cred = null,
        _user = null,
        id = Date.now();
    var eventEmitter = new EventEmitter();
    var _listenToLogin = function(action) {
        if (action.actionType === 'LOGIN_USER') {
            _cred = action.cred;
            _user = action.user;
            eventEmitter.emit('CHANGE');
        } else if (action.actionType === 'LOGOUT_USER') {
            _cred = null;
            _user = null;
            eventEmitter.emit('CHANGE');
        }
    };
    AppDispatcher.register(_listenToLogin.bind(this));
    var user = function() {
        return _user;
    };
    var cred = function() {
        return _cred;
    };
    var addChangeListener = function(cb) {
        eventEmitter.on('CHANGE', cb);
    };
    var removeChangeListener = function(cb) {
        eventEmitter.removeListener('CHANGE', cb);
    };
    var isLoggedIn = function() {
        return (!!_user);
    };
    return ({
        id: id,
        user: user,
        cred: cred,
        isLoggedIn: isLoggedIn,
        addChangeListener: addChangeListener,
        removeChangeListener: removeChangeListener
    });
})();
module.exports = LoginStore;

正如您所看到的,我希望LoginStore是Singleton,所以当我从代码的不同部分访问它时,它具有相同的状态。

以下是我使用mixins的方式:

关于.js:

'use strict';

var React = require('react');
var AuthMixins = require('./mixins/LoginMixins');

var About = React.createClass({
    displayName: 'About',
    mixins: [AuthMixins],
    getDefaultProps: function() {
        return {
            message: 'Default Prop for About page'
        };
    },
    render: function() {
        return (<div>
        {this.props.message}
        </div>);
    }
});

module.exports = About;

现在,问题是每次加载About时,都会加载LoginStore的新实例。 (不尊重我们希望它是单身的这个事实)作为回报,它表明用户没有登录。

0 个答案:

没有答案