美文网首页
react + redux 笔记

react + redux 笔记

作者: Lzzzzzq | 来源:发表于2017-01-09 16:14 被阅读0次

** Redux是个状态容器,只能通过发起action改变state,这种集中管控的做法让状态管理和预测变的简单。组件只是state的展现形式而已!React只是一个界面库而已!**

先考虑Redux是怎么运作的:首先store中维护了一个state,我们dispatch一个action,接下来reducer根据这个action更新state。

映射到我们的React应用中,store中维护的state就是我们的app state,一个React组件作为View层,做两件事:render和响应用户操作。于是connect就是将store中的必要数据作为props传递给React组件来render,并包装action creator用于在响应用户操作时dispatch一个action。

Provider

provider 是 react-redux 提供的组件,用来把 store 和视图绑定在一起

<Provider store={store}>
    <App />
</Provider>

<Provider store={store} key="provider"> 
    <Router history={history} routes={routes} />  //使用路由
</Provider>

Store

store 即唯一的 state tree , store 会根据 reducer 进行初始化,每当被调用的时候都会返回一个新的 state

Reducer

redux 通过 reducers 来负责管理整个应用的State树,而 reducers 可以被分成一个个 reducer

const initialItems = Immutable.List([1,2,3]);
 
export default function items(state = initialItems, action) {
    switch(action.type) {
        case ADD_ITEM:
            return state.push( state.size !=0 ? state.get(-1)+1 : 1 );
        case DELETE_ITEM:
            return state.delete( state.indexOf(action.item) );
        case DELETE_ALL:
            return state.clear();
        default:
            return state;
    }
}

redux 提供的 combineReducers 函数可以帮助我们把 reducer 组合在一起,这样我们就可以把 reducers 拆分成一个个小的 reducer 来管理 store了

import { combineReducers } from 'redux';
import items from './items';
import filter from './filter';
 
const rootReducer = combineReducers({
  items,
  filter
});
 
export default rootReducer;

Action

actionType

export const ADD_ITEM = 'ADD_ITEM';
export const DELETE_ITEM = 'DELETE_ITEM';
export const DELETE_ALL = 'DELETE_ALL';
export const FILTER_ITEM = 'FILTER_ITEM';

action

export function deleteItem(item, e) {
    return {
       type: DELETE_ITEM,
       item
    }
}
export function deleteAll() {
    return {
       type: DELETE_ALL
    }
}

Dispatch

执行action

import Store from 'store';

Store.dispatch({
  type: "ARRANGE_VIEWING",
  data: {
    model: "Model S",
    id: "123"
  }
});

相关文章

网友评论

      本文标题:react + redux 笔记

      本文链接:https://www.haomeiwen.com/subject/ecqfbttx.html