React/reflux如何进行正确的异步调用

Dee*_*psy 1 javascript asynchronous reactjs react-jsx refluxjs

我最近开始学习ReactJS,但我对异步调用感到困惑.

假设我有一个带有用户/通过字段和登录按钮的登录页面.组件看起来像:

var Login = React.createClass({

    getInitialState: function() {
        return {
            isLoggedIn: AuthStore.isLoggedIn()
        };
    },

    onLoginChange: function(loginState) {
        this.setState({
            isLoggedIn: loginState
        });
    },

    componentWillMount: function() {
        this.subscribe = AuthStore.listen(this.onLoginChange);
    },

    componentWillUnmount: function() {
        this.subscribe();
    },

    login: function(event) {
        event.preventDefault();
        var username = React.findDOMNode(this.refs.email).value;
        var password = React.findDOMNode(this.refs.password).value;
        AuthService.login(username, password).error(function(error) {
            console.log(error);
        });
    },

    render: function() {

        return (
                <form role="form">
                    <input type="text" ref="email" className="form-control" id="username" placeholder="Username" />
                    <input type="password" className="form-control" id="password" ref="password" placeholder="Password" />
                    <button type="submit" className="btn btn-default" onClick={this.login}>Submit</button>
                </form>
        );
    }
});
Run Code Online (Sandbox Code Playgroud)

AuthService看起来像:

module.exports = {
    login: function(email, password) {
        return JQuery.post('/api/auth/local/', {
            email: email,
            password: password
        }).success(this.sync.bind(this));
    },

    sync: function(obj) {
        this.syncUser(obj.token);
    },

    syncUser: function(jwt) {
        return JQuery.ajax({
            url: '/api/users/me',
            type: "GET",
            headers: {
                Authorization: 'Bearer ' + jwt
            },
            dataType: "json"
        }).success(function(data) {
            AuthActions.syncUserData(data, jwt);
        });
    }
};
Run Code Online (Sandbox Code Playgroud)

操作:

var AuthActions = Reflux.createActions([
  'loginSuccess',
  'logoutSuccess',
  'syncUserData'
]);

module.exports = AuthActions;
Run Code Online (Sandbox Code Playgroud)

并存储:

var AuthStore = Reflux.createStore({
    listenables: [AuthActions],

    init: function() {
        this.user = null;
        this.jwt = null;
    },

    onSyncUserData: function(user, jwt) {
        console.log(user, jwt);
        this.user = user;
        this.jwt = jwt;
        localStorage.setItem(TOKEN_KEY, jwt);
        this.trigger(user);
    },

    isLoggedIn: function() {
        return !!this.user;
    },

    getUser: function() {
        return this.user;
    },

    getToken: function() {
        return this.jwt;
    }
});
Run Code Online (Sandbox Code Playgroud)

因此,当我单击登录按钮时,流程如下:

Component -> AuthService -> AuthActions -> AuthStore
Run Code Online (Sandbox Code Playgroud)

我直接用AuthService调用AuthService.login.

我的问题是我做得对吗?

我应该使用动作preEmit并执行:

var ProductAPI = require('./ProductAPI')
var ProductActions = Reflux.createActions({
  'load',
  'loadComplete',
  'loadError'
})

ProductActions.load.preEmit = function () {
     ProductAPI.load()
          .then(ProductActions.loadComplete)
          .catch(ProductActions.loadError)
}
Run Code Online (Sandbox Code Playgroud)

问题是preEmit是它使组件的回调更复杂.我想学习正确的方法,并找到使用ReactJS/Reflux堆栈放置后端调用的位置.

dam*_*nmr 6

我也使用Reflux,我使用不同的方法进行异步调用.

在vanilla Flux中,异步调用放在操作中.

在此输入图像描述

但在Reflux中,异步代码在商店中效果最好(至少在我看来是这样):

在此输入图像描述

因此,特别是在您的情况下,我将创建一个名为"login"的Action,它将由组件触发并由将启动登录过程的商店处理.一旦握手结束,商店将在组件中设置一个新状态,让它知道用户已登录.同时(this.state.currentUser == null例如)组件可能会显示加载指示符.