redux基本使用

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));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值