Flux 是由 Facebook 提出單向資料流的一個設計概念,並不是一個程式庫,它最重要的思維是單向資料流。
Unidirectional Data Flow
Single Source of Truth
Started by Dan Abramov in the conference of the topic "Hot Reloading with Time Travel" in React Europe 2015
Evolution of the ideas by Flux.
Inspired by Elm architecture
Without Redux
With Redux
Action
View
Dispatcher
Store A
Store B
Store C
View
Action
Reducer B
Reducer C
Flux
Redux
state
state
state
state
state
state
Middleware
Reducer A
Store
Flux
Redux
{
type: ADD_TODO,
text: 'Build my first Redux app'
}
type 是必要的,表示要執行的動作
function requestAddTodo() {
return {
type: ADD_TODO,
text: 'Build my first Redux app'
};
}
function requestAddTodo() {
dispatch({
type: ADD_TODO,
text: 'Build my first Redux app'
});
}
Flux
Redux
產生 Action 的 pure func
=(state, action ) => new state
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
default:
return state;
}
}
//Flux
var firstStore = {
first: 1
}
var secondStore = {
second: 2
}
//Redux
var state = {
firstState: {
first: 1
},
secondState: {
second: 2
}
}
store.dispatch (action):
接收 action 物件,並將狀態改變邏輯委派給 reducer
//直接dispatch action
store.dispatch({type : 'ADD_TODO'});
//dispatch 經由 action creator
store.dispatch(addTodo());
function addTodo(text) {
return {
type: 'ADD_TODO',
text
}
}
store.subscribe (listener):
讓 View 監聽state來重新render
//讓listener(render view function)去監聽store裡state的變化
並且一旦state發生變化,就觸發這個function
store.subscribe(listener);
store.getState ():
讓 View 能存取state物件
//要拿到當前的state資料,就要通過呼叫getState來取得
const state = store.getState();
Action
Reducer
store.dispatch
Action
Reducer
dispatch API
Middleware
在 action 和 reducer 之間的一個中介層,
目的是在 dispatch 前先對action做一些處理
//Middleware
({ dispatch, getState }) => (nextDispatch) => new dispatch
//applyMiddleware的使用方式
const { createStore, applyMiddleware } = Redux;
const store = createStore(
reducer,applyMiddleware(middleware1, middleware2)
);
For Chrome
from Chrome Web Store
or build it with npm i && npm run build:extension and load the extension's folder ./build/extension
or run it in dev mode with npm i && npm start and load the extension's folder ./dev.
Usage
replace
const store = createStore(reducer);
to
const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());