actionType.js
随着项目大型化,所以要抽取出来一个actionType.js文件来记录各种actionType常量
export const SET_CURRENTINDEX ='SET_CURRENTINDEX';
store.js
import { createStore } from 'redux';
import rootReducer from '../reducers';
const store = createStore(rootReducer,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
export default store;
action.js
Action 是把数据从应用(译者注:这里之所以不叫 view 是因为这些数据有可能是服务器响应,用户输入或其它非 view 的数据 )传到 store 的有效载荷。它是 store 数据的唯一来源。一般来说你会通过 store.dispatch() 将 action 传到 store。
import * as types from '../actionTypes';
import store from '../store';
export const IndexActionCreators = {
SetCurrentIndex(payload){
return {
type :types.SET_CURRENTINDEX,
payload
}
}
}
reducers.js
Reducers 指定了应用状态的变化如何响应 actions 并发送到 store 的, actions 只是描述了有事情发生了这一事实,并没有描述应用如何更新 state。
import { combineReducers } from 'redux';
import * as types from '../actionTypes';
const rootReaducer = combineReducers({
CurrentIndex
})
function CurrentIndex(preState = 0 , action ){
switch( action.type ){
case types.SET_CURRENTINDEX:
return action.payload
default :
return preState;
}
}
组件.js
dispatch的作用是分发 action,这是触发 state 变化的惟一途径。
store.dispatch(IndexActionCreators.SetCurrentIndex(index));