zoukankan      html  css  js  c++  java
  • [Redux] Store Methods: getState(), dispatch(), and subscribe()

    console.clear();
    const counter = (state = 0, action) => {
      switch (action.type) {
        case 'INCREMENT':
          return state + 1;
        case 'DECREMENT':
          return state - 1;
        default:
          return state;
      }
    } 
    
    // Create a store
    const {createStore} = Redux;
    // Store hold the state, can accept a reducer function
    const store = createStore(counter);
    
    let currentState = store.getState();
    console.log(currentState); // 0
    
    store.dispatch( {type: 'INCREMENT'} );
    console.log(store.getState()); // 1
    
    store.subscribe( () => {
      document.body.innerText = store.getState();
    });
    
    document.addEventListener('click', ()=>{
      store.dispatch( {type: 'INCREMENT'} );
    })

    If we run we will miss the first init state, it starts from '2'...

    So we need to call it before subscribe:

    console.clear();
    const counter = (state = 0, action) => {
      switch (action.type) {
        case 'INCREMENT':
          return state + 1;
        case 'DECREMENT':
          return state - 1;
        default:
          return state;
      }
    } 
    
    // Create a store
    const {createStore} = Redux;
    // Store hold the state, can accept a reducer function
    const store = createStore(counter);
    
    let currentState = store.getState();
    console.log(currentState); // 0
    
    store.dispatch( {type: 'INCREMENT'} );
    console.log(store.getState()); // 1
    
    const render = ()=> {
      document.body.innerText = store.getState();
    }
    render();
    store.subscribe( render);
    
    document.addEventListener('click', ()=>{
      store.dispatch( {type: 'INCREMENT'} );
    })
  • 相关阅读:
    Airtest环境搭建及介绍
    再谈PHP错误与异常处理
    Composer基础
    PHP中this,self,parent的区别
    3种方法轻松处理php开发中emoji表情的问题
    php防注入和XSS攻击通用过滤.
    mysql where in 数组解决小tips
    记录搜索关键字到数据库
    获取用户id的方法
    file_get_contents('php://input') 数据如何转换成数组
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4993492.html
Copyright © 2011-2022 走看看