本文根据 Devhints / Redux 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2018-01-17。
创建 Store(状态存储)
import { createStore } from 'redux'
// Reducer
function counter (state = { value: 0 }, action) {
switch (action.type) {
case 'INCREMENT':
return { value: state.value + 1 }
case 'DECREMENT':
return { value: state.value - 1 }
default:
return state
}
}
let store = createStore(counter)
// Optional - you can pass `initialState` as a second arg
let store = createStore(counter, { value: 0 })
Store 由一个 reducer 函数创建,该函数接收当前状态 state,并返回一个新的状态 state 具体取决于 action 传入的参数。
使用 Store
let store = createStore(counter)
// Dispatches an action; this changes the state
store.dispatch({ type: 'INCREMENT' })
store.dispatch({ type: 'DECREMENT' })
// Gets the current state
store.getState()
// Listens for changes
store.subscribe(() => { ... })
通过分发 (dispatch) action 来改变 Store 的状态。
React Redux
Provider
import { Provider } from 'react-redux'
React.render(
<Provider store={store}>
<App />
</Provider>, mountNode)
该 <Provider> 该组件使 Store 能够在你的 React 组件中使用。你需要它,以便能够使用 connect().
映射状态 (Mapping state)
import { connect } from 'react-redux'
// A functional React component
function App ({ message, onMessageClick }) {
return (
<div onClick={() => onMessageClick('hello')}>
{message}
</div>
)
}
// Maps `state` to `props`:
// These will be added as props to the component.
function mapState (state) {
return { message: state.message }
}
// Maps `dispatch` to `props`:
function mapDispatch (dispatch) {
return {
onMessageClick (message) {
dispatch({ type: 'click', message })
}
}
}
// Connect them:
export default connect(mapState, mapDispatch)(App)
简写属性
export default connect(
(state) => ({
message: state.message
}),
(dispatch) => ({
onMessageClick: (message) => {
dispatch({ type: 'click', message })
}
})
)(App)
与上述相同,但更简洁。
组合 Reducer
const reducer = combineReducers({
counter, user, store
})
将多个 Reducer 合并为一个 Reducer 函数。参见: combineReducers (redux.js.org)
中间件(Middleware)
签名
// noop middleware
const logger = store => dispatch => action { dispatch(action) }
const logger = store => {
// This function runs on createStore().
// It returns a decorator for dispatch().
return dispatch => {
// Runs on createStore(), too.
// It returns a new dispatch() function
return action => {
// Runs on every dispatch()
}
}
}
中间件(Middleware)本质上就是……的装饰器, dispatch() 旨在让你能够处理不同类型的 Action,并在接收到 Action 时执行各类任务。
应用中间件
const enhancer = applyMiddleware(logger, thunk, ...)
const store = createStore(reducer, {}, enhancer)
参考资料
- Redux (npmjs.com)
- React-redux (npmjs.com)
- 与 React 配合使用 (redux.js.org)