前言
在最近的项目中接触了redux,看了一遍官方文档。在实际使用中也算是摸到一点门道。在这里写篇文章总结一下吧。
这里我就不写原理了,去官网看就行了,这里就写写自己的理解。
Redux的组成
- Action 其实就是一个动作的名字,一个action的类型是Object,通过type属性来区分action,如:
export const getTopics = (tab, page) => { return function (dispatch) { let path = baseUrl + "/topics/?tab=" + tab + "&page=" + page; dispatch({ type: "IS_LOADING" }); fetch(path) .then( response => response.json(), error => console.log('An error occurred.', error) ) .then(res => { dispatch({ type: "END_LOADING" }); dispatch({ type: "GET_TOPICS", topics: res.data, tab, page }) }) } }
- Reducer 分发器,负责根据对应的action,进行处理并返回state,如:
export const topic = (state = {}, action) => { switch (action.type) { case "GET_TOPICS": return ( { topics: action.topics, tab: action.tab, page: action.page }) default: return state; } }
- store 一个应用只能有一个store,根据reducer生成store,使用了异步action,所以需要添加thunkMiddleware中间件,如:
const store = createStore(rootReducer, applyMiddleware(thunkMiddleware, loggerMiddleware))
搭配React使用
- 先定义action
- 定义reducer
- 定义store
- 然后把store绑定到react应用父组件上,我是绑定到<Router />上,如:
ReactDOM.render( <Provider store={store}> <Router history={browserHistory}> <Route path='/' component={Home} /> </Router> </Provider> , document.getElementById('root'));
5.在Home组件里定义mapStateToProps函数和mapDispatchToProps函数,如:
const mapStateToProps = state => ({
tab: state.tab,
page: state.page
})
const mapDispatchToProps = dispath => ({
getTopics: (topics, tab, page) => dispath(getTopics(topics, tab, page))
})
6.通过react-redux带的connect连接store,这样一整套流程就走下来了。如:
export default connect(mapStateToProps, mapDispatchToProps)(Home);
总结
- 在react中组件通过mapDispatchToProps函数调用对应action
- 触发对应reducer,更新state
- 在通过mapStateToProps函数把state绑定到组建的Props中