我的状态存储在打字稿

时间:2020-10-21 13:30:03

标签: javascript typescript rxjs state

我不知道自己在做什么。我的扫描类型未知,我认为除此之外,还有许多其他问题。

我知道这与扫描的工作方式有关,我将getState替换为subscribe(肯定是错误的),因为它出错了,我无法修复。

import Rx from 'rxjs';
import { scan, share } from 'rxjs/operators';
import { reducers } from './reducers/index';

export default function createStore(initialState, reducers) {
  const subject = new Rx.Subject();

  const store = subject.pipe(scan(
    (state, action) => {
      if (!action || !action.type || ! (action.type in reducers)) {
        console.error('Action not registered'); 
        console.error(action); 
        console.error(action.type); 
        return state; 
      }

      return reducers[action.type].call(null, state, action);
    },
    initialState || {}
  )).pipe(share());

  const stateSymbol = Symbol('state');
  store.subscribe(state => {
    store[stateSymbol] = state;
  }, (err) => {
    console.error('Error in the store', err);
  });
  store.subscribe = () => store[stateSymbol];

  function dispatch(action) {
    return typeof action === 'function'
      ? action.call(null, subject, dispatch)
      : subject.next(action);
  }

  return {
    store,
    dispatch,
  };
}

0 个答案:

没有答案