Programming

context

通过 独立变量 做 context 值容器,提供一个 provide 来输入,consume 来输出

  1. const GlobalState = {
  2. context: [],
  3. }
  4. export const createEffectContext = <T = any>(defaultValue?: T) => {
  5. let index: number
  6. return {
  7. provide(value?: T) {
  8. index = GlobalState.context.length
  9. GlobalState.context[index] = isValid(value) ? value : defaultValue
  10. },
  11. consume(): T {
  12. return GlobalState.context[index]
  13. },
  14. }
  15. }