码迷,mamicode.com
首页 > 其他好文 > 详细

[Redux] Store Methods: getState(), dispatch(), and subscribe()

时间:2015-11-25 06:37:07      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

 

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‘} );
})

 

[Redux] Store Methods: getState(), dispatch(), and subscribe()

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/4993492.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!