实际上我们在实际的业务组件中需要使用就是两个函数,一个是connect函数,另外一个就是provider组件,直接将Provider映射为组件,在组件标签上将store传递给各业务的子组件。 connect函数的作用就是将我们的实际的业务组件与store进行关联,让我们在组件中可以方便的使用store以及修改store的相关的方法。
1、使用react-redux来改造计数器案例
原理:redux代替我们封装了connect函数和context函数。
# 在父组件中进行使用 数据传递给子组件import React, { PureComponent } from 'react'import About from './16_react-redux/pages/About'import Home from './16_react-redux/pages/Home'// 引入StoreContext// import StoreContext from './16_react-redux/utils/context'// 引入store// import store from './16_react-redux/store'# 使用react-redux中的Provider 直接react-redux提供的高阶组件Provider 将组件映射为标签即可,将我们实际的业务组件放置于这个Provider高阶组件中即可import { Provider } from 'react-redux'import store from './16_react-redux/store'export default class App extends PureComponent {render() {return (<div>{/* 为组件提供context */}# 需要注意的是 我们在使用context的时候,在高阶组件中传值使用的是value属性,但是在react-redux中,他要求我们必须 使用store来传递数据 非常重要 不用这个属性的话 数据将无法进行传递<Provider store={store}><About /><hr/><Home /></Provider></div>)}}
1.1 React-redux在实际业务组件中的使用
import React, { PureComponent } from 'react'// import connect from '../utils/connect'// 引入react-redux中的connect函数 非常重要# import { connect } from 'react-redux'import {incrementAction, addNumberAction} from '../store/actionCreators'class About extends PureComponent {render() {return (<div><h2>about组件</h2><h2>当前技术:{this.props.counter}</h2><button onClick={() => this.props.btn1Click() }>+1</button><button onClick={() => this.props.btn2Click(5) }>+5</button></div>)}}const mapStateToProps = state => {return {counter: state.counter}}const mapDispatchToProps = dispatch => {return {btn1Click() {dispatch(incrementAction())},btn2Click(num) {dispatch(addNumberAction(num))}}}// 使用react-redux中的contect函数export default connect(mapStateToProps, mapDispatchToProps)(About)
1.2 React-Redux的使用总结
// react-redux的使用原理总结:1、安装react-redux第三方库yarn add react-redux2、在具体的业务组件中直接使用connect函数import { connect } from 'react-redux'// 定义变量const mapStateToProps = {}const mapStateToDispatch = {}export default connect(mapStateToProps, mapStateToDispatch)(ComponentName)3、在跟组件中向下传递storeimport store from 'store/index.js';使用Providerimport { Provider } from 'react-redux';映射为相应的标签 相当于将store以全局变量的方式都传递给了所有的子组件<Provider store={store}><App /><Provider>4、在类组件中可以直接使用this.props的属性来访问全局传入的store对象在函数式组件中直接使用props来接收跟组件传递过来的参数
