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'} );
    })
  • 相关阅读:
    大整数相加算法
    java中String和char的区别
    Git命令
    Dart随记
    用nodejs或者Chrome控制台的js对URI进行编码或解码
    Rust执行cmd或shell命令
    cargo expand用于查看被宏隐藏的代码
    Blocking waiting for file lock on package cache
    Rust生命周期之个人理解
    Rust为基础类型实现Trait
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4993492.html
Copyright © 2011-2022 走看看