一、作用
react-redux插件可以使redux的使用变得更加简单。
二、使用
首先,要创建store和reducer
- 创建store
import { createStore, compose, applyMiddleWare } from 'redux'
import reducer from './reducer'
import thunk from 'redux-thunk'
// 设置调试工具
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
// 设置中间件
const enhancer = composeEnhancers(
// 使用中间件
applyMiddleware(thunk)
);
// 创建store
const store = createStore(reducer, enhancer);
// 导出store
export default store;
- 创建reducer
const defaultState = {
// some code here
}
export default (state = defaultState, action) => {
switch(action.type){
// some code here
default: return state;
}
}
然后,要在需要使用store的最上层组件中绑定store
import React, { Component } from 'react'
import { Provider } from 'react-redux'
import 'store' from './store'
class App extends Component{
render(){
return (
<Provider store = { store }>
{ // some code here }
</Provider>
)
}
}
export default App;
最后,在使用store的各部分组件中使用connect将map,dispatch和props绑定并导出
import React, { Component } from 'react'
import { connect } from 'react-redux'
class Header extends Component{
// 在this.props中可以访问到connect传递过来的属性和方法
render(){
//some code here
}
}
// 将state传递到props,这里的state即store中的state
const mapStateToProps = (state) => ({
search: state.search,
//.....
});
// 将dispatch传递到props
const mapDispatchToProps = (dispatch) => ({
getSearch(){
dispatch(...)
},
// ......
});
export default connect(mapStateToProps, mapDispatchToProps)(Header);
网友评论