更新的商店价值不影响所有组件吗?

时间:2019-02-13 16:52:55

标签: reactjs state flux dom-events

我正在设置一个反应通量存储库,可以通过axios调用执行登录并存储登录状态。登录后,我有许多组件要检查身份验证状态。

换句话说,当商店更新时,如何在许多组件中自动获取更新的值。

我的store.js如下所示

import { EventEmitter } from 'events';
import setAuthorizationToken from './setAuthorizationToken';
import axios from 'axios';
import history from './../Components/history';

class DataStore extends EventEmitter {
    triggerError = ( title, message) => this.emit('ERROR', {title, message});
    triggerResonse = ( funcName, data) => this.emit(funcName, { ...data });

    data = {}
    saveUserData = (userData) => { this.data.user = userData }
    getUserData = (key) => { return this.data.user[key] }

    requestLogin = async (d) => {
        var payload = {
            email: d.email,
            password: d.password,
            remember: false
        };
        var errorMessage = {
            title: 'Login Failed',
            message: 'Please check your Username & Password, before proceeding ahead'
        }

        // var response = await Api.login(payload);
        var response = await axios.post('http://localhost:5000/login', payload);
        console.log(response.data.token);
        const token = response.data.token;
        localStorage.setItem('jwtToken', token);
        setAuthorizationToken(token);

        this.processResponse('LOGIN', response, errorMessage);
    }

    requestSignup = async (d) => {
        var payload = {
            fname: d.fname,
            lname: d.lname,
            email: d.email,
            password: d.password,
            passwordc: d.passwordc,
            remember: false
        };

        console.log(payload);

        var errorMessage = {
            title: 'SignUp Failed',
            message: 'Please check your details, before proceeding ahead'
        }

        // var response = await Api.register(payload);
        var response = await axios.post('http://localhost:5000/register', payload);
        console.log(response);
        this.processResponse('REGISTER', response, errorMessage);
        history.push('/');
    }

    processResponse = (eventName, response, error ) =>
        response.ok ? this.triggerResonse(eventName, response.data) : this.triggerError(error.title, error.message )
}

const dataStore = new DataStore();
window.cd = dataStore;
export default dataStore;

0 个答案:

没有答案