Actionreact
function addTodo(text) { return { type: ADD_TODO, text } }
type
屬性是必須的。git
Reducergithub
function todoApp(state = initialState, action) { switch (action.type) { case ADD_TODO: return Object.assign({}, state, { todo: action.todo }) default: return state } }
一、須要一個case
與action
的type
一致。web
二、必須在switch
的defautl
返回原state
。chrome
Storenpm
state
getState()
方法,能夠獲取state
dispatch(action)
設置state
subscribe(listener)
註冊和取消註冊監聽事件是Redux的React實現,可參考 Official React bindings for Redux.
yarn add redux react-redux //or npm i redux react-redxu
表現性組件redux
只負責顯示UI的組件。ide
例如:flex
<div></div>
容器性組件google
不處理UI的組件,也不處理數據,只爲UI組件提供數據的組件。
例如:
connect(state => state)(<YourComponent />)
除以上兩種組件之外的組件。
咱們以一個計數器的例子來講明如何使用React-redux.
設計表現性組件
須要:顯示當前計數,默認爲0;累加按鈕,每次單擊加1;遞減按鈕,每次單擊減1;重置按鈕,單擊將計數設置爲0。
import React from 'react'; export default ({counter = 0}) => { const styles = { display: 'flex', justifyContent: 'space-around' }; return ( <div> <h1>當前計數爲:{counter}</h1> <div style={styles}> <button>加</button> <button>減</button> <button>重置</button> </div> </div> ); };
設置容器性組件
目的是將表現性組件中的數據抽離出去交給redux管理,而後經過容器性組件將redxu與表現性組件關聯起來。
import { connect } from 'react-redux'; import CounterIndex from '../components/chapter03/Counter'; export default connect(state => ({ ...state.counterRedux }))(({ counter, dispatch }) => <CounterIndex counter={counter} dispatch={dispatch} />);
Action
export const COUNTER_ACTION = 'COUNTER_ACTION'; export const addActioner = ({counter}) => { return {type: COUNTER_ACTION, counter: counter + 1}; }; export const subActioner = ({counter}) => { return {type: COUNTER_ACTION, counter: counter - 1}; }; export const resetActioner = () => { return {type: COUNTER_ACTION, counter: 0}; };
Reducer
import { COUNTER_ACTION } from '../actions/CounterAction'; export default (state, action) => { switch (action.type) { case COUNTER_ACTION: return { ...state, counter: action.counter }; default: return state; } }
Store
import React from 'react'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import CounterReducer from '../reducers/CounterReducer'; let store = createStore(CounterReducer); export default ({ children }) => <Provider store={store}>{children}</Provider>
console日誌
安裝redux-logger組件:yarn add redux-logger --dev
。
而後加入到redux store中便可:
import { createLogger } from 'redux-logger'; store = createStore(reducers, createLogger());
例如:
redux擴展程序
須要在Chrome應用市場安裝Redux DevTools.
而後在store中使用加強功能將redux-logger加入便可:
const logger = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__(createLogger()); store = createStore(reducers, logger);
推薦閱讀《React 手稿》