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'} );
    })
  • 相关阅读:
    PL/SQL跨库查询数据
    oracle 两个时间相减
    导出Excel格式数据
    Java导出pdf文件数据
    $.ajax相关用法
    oracle 删除掉重复数据只保留一条
    常用Oracle操作语句
    JS请求服务器,并返回信息,请求过程中不需要跳转页面
    tomcat部署web项目的3中方法
    Date()日期转换和简单计算
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4993492.html
Copyright © 2011-2022 走看看