react-redux学习记录

1、react-redux中的两个核心api Provider(提供器) connect(连接器)。顾名思义,Provider将store中的数据提供给它内部的组件,在组件中通过 connect 方法对store中的数据进行接收。

在react项目入口文件index.js中,引入store和 react-redux中的Provider组件

// index.js
import store from './store'
import {Provider} from 'react-redux'
const App = {
  <Provider store={store}>
    <ChildComponent/>
  </Provider>
}
ReactDom.render(App,document.getElementById('root'))

Provider 连接了store,则它内部所有的子组件都可以接收使用store
2、Provider将store提供给了组件,在组件中通过connect方法将组件与store进行连接

// component
// 组件中引入connect方法
import {connect} from 'rect-redux'
//组件最终导出connect方法,并将组件名称传入
export default connect(mapStateToProps, mapDispatchToProps)(ChildComponent)

connect方法接收三个参数,最后一个参数为组件的名称,
第一个参数 mapStateToProps为一个方法,该方法将store中的数据映射到组件的props中

// mapStateToProps接收一个state参数,state即store中数据
const mapStateToProps =(state)=>{
  return {
    inputValue:state.inputValue,
    list: state.list
  }
}

则在组件中可以通过 this.props 获取store中的数据。
3、相反的如果组件想更改store中的数据,必须通过store的dispatch方法,所以connect方法中的第二个参数mapDispatchToProps,是定义一些通信的方法,在方法中可以直接调用store中的dispatch,并将定义的方法映射到props中。所以组件中可以直接调用props中的方法进行store通信修改数据。

const mapDistPatchToProps=(dispatch)=>{
 return {
    // 定义需要修改数据的方法并映射到props中
   inputChange(e){
      const action = {
        type: 'input_change',
        value: e.target.value
      }
      dispath(action)
   }
 }
}

关系大致可以理解为
这里写图片描述
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_39786582/article/details/82493143