赞
踩
import { createStore } from 'redux';
import reducer from './reducer'
const store = createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
export default store;
import { CHANGE_INPUT_VALUE,ADD_TODO_ITEM,DELETE_TODO_ITEM } from './actionTpyes' const defaultState = { inputValue:'', list: [] } // reducer 可以接收state,但是绝不能修改state export default (state = defaultState,action) => { if(action.type === CHANGE_INPUT_VALUE) { const newState = JSON.parse(JSON.stringify(state)); newState.inputValue = action.value; return newState } if(action.type === ADD_TODO_ITEM) { const newState = JSON.parse(JSON.stringify(state)); newState.list.push(newState.inputValue); newState.inputValue = '' return newState } if(action.type === DELETE_TODO_ITEM) { const newState = JSON.parse(JSON.stringify(state)); newState.list.splice(action.index,1) return newState } return state; }
constructor(props) {
super(props);
store.subscribe(this.handleStoreChange)
}
handleItemDelete(index) {
const action = {
type: DELETE_TODO_ITEM,
index
}
store.dispatch(action)
}
subscribe 这个函数是用来去订阅 store 的变化,比如你每次对 store 进行 dispatch(action) 都会触发 subscribe 注册的函数调用,这个在实际情况不是必须要的,看自己的应用场景,比如你想监控 store 的全局变化时 可以用 subscript 订阅一下,然后作一些反应
每次通过dispatch 修改数据的时候,其实只是数据发生了变化,如果不手动调用 render方法,页面上的内容是不会发生变化的。
但是每次dispatch之后都手动调用很麻烦啊,所以就使用了发布订阅模式,监听数据变化来自动渲染。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。