zoukankan      html  css  js  c++  java
  • 简单实现一个redux

    <!DOCTYPE html>
    <html lang="zh">
      <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></title>
        <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
        <script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
      </head>
      <body>
        <div id="root"></div>
        <script type="text/babel">
          function createStore(reducer) {
            let state = {
             num: 0
            };
            let listeners = []
            const getState = () => state;
            const dispatch = action => {
              state = reducer(state, action)
              listeners.forEach(listen => listen())
            }
            const subscribe = listener => {
              listeners.push(listener);
              return listeners.filter(item => item !== listener);
            }
            return { getState, dispatch, subscribe}
          }
          const store = createStore(reducer)
          function reducer(state, action) {
            if (action.type === 'add') {
              return { ...state, num: state.num + action.payload }
            }
            return state;
          }
          class App extends React.Component {
              add() {
                store.dispatch({ type: 'add', payload: 5 })
                console.log('state', store.getState())
              }
              render() {
                return (
                  <div>
                    <div>Num: {store.getState().num}</div>
                    <button onClick={this.add}>+ 5</button>
                  </div>
                )
              }
            }
           const render = () => {
             ReactDOM.render(<App />, document.getElementById('root'))
           }
           store.subscribe(render)
           render()
        </script>
      </body>
    </html>
    
  • 相关阅读:
    敏捷软件开发实践-Release Process/Release Plan(转)
    《敏捷软件开发-原则、方法与实践》-Robert C. Martin读书笔记(转)
    测试RESTful API利器-Postman
    backbone.js初探(转)
    JavaScript有关的10个怪癖和秘密(转)
    Restful Web Service初识
    JSTL标签库的使用
    JavaScript处理JSON
    绑定QQ登录 PHP OAuth详解(转)
    mysql if exist坑
  • 原文地址:https://www.cnblogs.com/liea/p/13254258.html
Copyright © 2011-2022 走看看