redux基本实现原理

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>redux原理</title>
</head>
<body>
  <p>02-创建了story方法</p>
  <div>
    <button onclick="store.dispatch({type:'JIAN', n:1 })">-</button>
    <span id="countDisplay">10</span>
    <button onclick="store.dispatch({type:'JIA', n:1 })" >+</button>
  </div>
  <script>
    // 获取元素
    const countDisplay = document.getElementById('countDisplay');

    // 定义初始数据
    const countStat = {
      count : 5
    }

    // 通过状态改变计算方法
    const changeState = (state,action) => {
      if(state ===  null) {
        return countStat
      }
      switch(action.type) {
        case 'JIAN':
        return {
          ...state,
          count : state.count - action.n
        }

          break;
        case 'JIA':
        return {
          ...state,
          count : state.count + action.n
          }

          break;

        default:
          return state
      }
    }


  const createStory = (reducer) => {
    let state = null
    const getState = () => state
    const listeners = []
    const subscribe = (listener) => listeners.push(listener)
    const dispatch = (action) => {
      state = changeState(state,action)
      listeners.forEach(listener => listener())
    }
    dispatch({})
    return {
      getState,
      dispatch,
      subscribe
    }
  }


  const store = createStory(changeState);

  const renderCount = () => {
    countDisplay.innerHTML = store.getState().count
  }
  renderCount();

  store.subscribe(renderCount)

  </script>
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容