react-redux
众所周知,Redux 是React 全家桶中重要的一员,它试图为 React 提供状态管理机制;个人理解,与Vue中的状态管理Vue-X相似。在使用react开发时,如果要将 Redux 和 React 结合起来使用,往往会选择一个额外的工具,即react-redux 。
react-redux 提供了两个重要的对象,provider 和 connect,前者使 React 组件可被连接(connectable),后者把 React 组件和 Redux 的 store 真正连接起来。
provider
Provider:提供器,在该组件里边的所有组件都可以使用 store,使 React 组件可被连接(connectable)
import { Provider } from 'react-redux'
import store from './store'
const App = (
<Provider store={store}>
<Home />
</Provider>
)
connect
connect:连接器,获取store数据,根据官方文档解释:Connects a React component to a Redux store.It does not modify the component class passed to it. Instead, it returns a new, connected component class, for you to use.
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])
connect方法接收四个参数,分别是 mapStateToProps,mapDispatchToProps,mergeProps和options。
1、mapStateToProps(state, ownProps)
mapStateToProps函数允许我们将 store 中的数据作为 props 绑定到组件上。
const mapStateToProps = (state, ownProps) => {
return {
count: state.count
}
}
2、mapDispatchToProps(dispatch, ownProps)
mapDispatchToProps函数将 action 作为 props 绑定到组件上。
const mapDispatchToProps = (dispatch, ownProps) => {
return {
increase: (...args) => dispatch(actions.increase(...args)),
decrease: (...args) => dispatch(actions.decrease(...args))
}
}