博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[AngularJS] Write a simple Redux store in AngularJS app
阅读量:7236 次
发布时间:2019-06-29

本文共 4226 字,大约阅读时间需要 14 分钟。

The first things we need to do is create a reducer: 

/** * CONSTANT * @type {string} */export const GET_CATEGORIES = "GET_CATEGORIES";/** * INIT VALUE */export const initialCategories = [  {id: 0, name: 'Development'},  {id: 1, name: 'Design'},  {id: 2, name: 'Exercise'},  {id: 3, name: 'Humor'}];/** * REDUCERS * @type {string} */export const categories = (state = initialCategories, {type, payload}) => {  switch(type) {    case GET_CATEGORIES:      return payload || state;    default:      return state;  }};

It has some default initialize data. What it does is just simply return the state.

 

Then let's create a gloable store for the app, which has two methods, getState, dispatch.  Two props: reducer, state.

class Store {  constructor(reducer, initialState) {    this.reducer = reducer;    this.state=  initialState;  }  getState() {     return this.state  }  dispatch() {     this.state = this.reducer(this.state, action);  }}

 

Once we got that, we are going to init our store:

import {categories, initialCategories} from './components/categories/category.state';import Store from './app.store';const store = new Store(categories, initialCategories);

We passed in categoreis reudcer and the initialCategories state.

 

To make it available to Angular APP. we need to make it injectable:

let appModule = angular.module('app', [    CommonModule.name,    ComponentsModule.name  ])    .value('store', store)

 

Then we can use it in our app:

class CategoriesController {  constructor(store) {    'ngInject';    angular.extend(this, {      store    });  }  $onInit() {    this.store.dispatch({type: GET_CATEGORIES});    this.categories = this.store.getState();  }}

 


 

 

Now we are going to simply the code a little bit, we going to make a subscribe method so that we don't need to call getState() method everytime after we dispatch an action.

You can think that the subscribe method is a just callback function which each time we dispatch an action, it will be called. And inside the callback function, we will call this.store.getState() to get the value.

class Store {  constructor(reducer, initialState) {    this.reducer = reducer;    this.state = initialState;    this.listeners = [];  }  getState() {    return this.state;  }  dispatch(action) {    this.state = this.reducer(this.state, action);    this.listeners.forEach((l) => l());  }  subscribe(listener) {    this.listeners = [      ...this.listeners,      listener    ];    // return an unsubscribe function    return () => {      this.listeners = this.listeners.filter(l => l !== listener);    }  }}export default Store;
class CategoriesController {  constructor($timeout, store) {    'ngInject';    angular.extend(this, {      $timeout,      store    });  }  $onInit() {    this.unsubscribe = this.store.subscribe(() => {       this.categories = this.store.getState();    });    this.store.dispatch({type: GET_CATEGORIES});  }}

 


 

 

Currently inside the dispatch() metod, we pass in an object with type and payload. It would be better if we can manage those action in a single place. There is where Action creator comes in to play.

/** * ACTIONS CREATOR */export const CategoriesActions = () => {  const getCategoreis = (categories) => {    return {type: GET_CATEGORIES, payload: categories}  };  const getCurrentCategory = (currentCategory) => {    return {type: GET_CURRENT_CATEGORY, payload: currentCategory}  };  return {    getCategoreis,    getCurrentCategory  };};

 

To make it avaiable to Angular App, we can create a factory for this:

let appModule = angular.module('app', [    CommonModule.name,    ComponentsModule.name  ])    .value('store', store)    .factory('CategoriesActions', CategoriesActions)  .component('app', AppComponent)

 

Then we can use it inside the controller:

constructor($timeout, store, CategoriesActions) {    'ngInject';    angular.extend(this, {      $timeout,      store,      CategoriesActions    });  }
$onInit() {    this.unsubscribe = this.store.subscribe(() => {       this.categories = this.store.getState();    });    this.store.dispatch(this.CategoriesActions.getCategoreis());  }
onCategorySelected(currentCategory) {    this.currentCategory = category(this.currentCategory, this.CategoriesActions.getCurrentCategory(currentCategory));  }

 

转载地址:http://xhofm.baihongyu.com/

你可能感兴趣的文章
[转载]浅谈组策略设置IE受信任站点
查看>>
【转】maven导出项目依赖的jar包
查看>>
JS实现文本复制与剪切
查看>>
s标签可以if elseif else
查看>>
每天一个linux命令(20):linux chmod命令
查看>>
MySQL复合分区
查看>>
[ACM] POJ 3687 Labeling Balls (拓扑排序,反向生成端)
查看>>
LeetCode - Permutation Sequence
查看>>
eval解析JSON中的注意点
查看>>
BootCamp支持软件6
查看>>
整数对(数学,思维)
查看>>
Could not open Selected VM debug port (8700) (转)
查看>>
VS中遇到的奇怪问题
查看>>
Leetcode: Median of Two Sorted Arrays. java.
查看>>
【探索】在 JavaScript 中使用 C 程序
查看>>
设定事件间隔和延迟
查看>>
Android中轻松显示Gif图片
查看>>
unity, yield return new WaitForSeconds(waitTime) 在 Time.timeScale=0下卡死
查看>>
dubbo配置文件报错解决思路
查看>>
getline()函数
查看>>