function counter(state = 0, action) { switch (action.type) { case ‘INCREMENT’: return state + 1; case ‘DECREMENT’: return state - 1; default: return state; } }
let store = createStore(counter);
store.subscribe(() => console.log(store.getState))
store.dispatch({ type: ‘INCREMENT’ })
<a name="vlTns"></a>
# 单向数据流概述
1. dispatch(action)
1. reducer -> newState
1. subscribe 触发通知
<a name="An2Ot"></a>
# react-redux
- <Provider>
- connect
- mapStateToProps mapDispatchToProps
<a name="gG2mx"></a>
# 异步 action
```jsx
export const addTodo = text => {
// 返回 action 对象
return {
type: 'ADD_TODO',
id: nextTodoID++,
text
}
}
import { createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
// 创建 store 时,作为中间件引入 redux-thunk
const store = createStore(rootReducer, applyMiddleware(thunk));
export const addTodoAsync = text => {
// 返回函数,其中有 dispatch 参数
return (dispatch) => {
fetch(url).then(res => dispatch(addTodo(res.text)))
}
}
redux 中间件
import { applyMiddleware, createStore } from 'redux';
import createLogger from 'redux-logger';
import thunk from 'redux-thunk':
const logger = createLogger () ;
const store = createStore(
reducer
applyMiddleware ( thunk, logger) //会按顺序执行
)
// 自己修改 dispatch,增加 logger
let next = store.dispatch;
store.dispatch = function (action) {
console.log('dispatching', action);
next(action);
console.log('next state', action);
}