Use react-redux to achieve data sharing

1. Introduction to react-redux

1.1. React-Redux is the official binding library between React and Redux. It provides the function of mapping Redux Store status to React component properties, and uses the Provider component to allow all descendant components in the component tree to obtain the Store.
Insert image description here
From the model diagram, we can know whether the UI component has any connection with redux. What
really deals with redux is the container component corresponding to the UI component.
Therefore, in order to simplify the file complexity, we can define the UI component and the container component in the same In a file,
just expose the container component.

2. Use of react-redux

2.1. Installation of react-redux

npm install react-redux

2.2. Create corresponding files
2.2.1. Since data sharing is to be achieved, two components must be created. Each component must create corresponding
action files and reducers files. You can refer to the previous article
2.2.2, how to define UI components and container components in the same file (example)

import React, {
    
     Component } from 'react'

import {
    
     creDecAction, creIncAction } from '../../redux/actions/count'

//引入 connect用于连接UI组件与redux
import {
    
    connect} from 'react-redux'

 class Count extends Component {
    
    

    //加法
    increment = ()=>{
    
    
      const {
    
    value} = this.selectNumber
      this.props.jia(value*1);
    
    }
    //减法
    decrement = ()=>{
    
    
      const {
    
    value} = this.selectNumber
      this.props.jian(value*1);
     
    }
    //奇数再加
    incrementIfOdd = ()=>{
    
    
      const {
    
    value} = this.selectNumber
      this.props.jia(value*1);
     
    }
    //异步加
    incrementAsync = ()=>{
    
    
      const {
    
    value} = this.selectNumber
      this.props.jia(value*1);
    }
    render() {
    
    
      const {
    
     count } = this.props
      return (
        <div>
          <h1>我是 Count组件 ,下方组件总人数为:{
    
    this.props.renSu} </h1>
          <h3>当前求和为: {
    
    count}</h3>
          <select ref={
    
    c=>this.selectNumber=c} >
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
          </select>
          <button onClick={
    
    this.increment}>+</button>
          <button onClick={
    
    this.decrement}>-</button>
          <button onClick={
    
    this.incrementIfOdd}>当前求和为奇数在加</button>
          <button onClick={
    
    this.incrementAsync}>异步加</button>
        </div>
      )
    }
  }

// a函数 的返回值为一个对象 作为状态传递给 UI组件
// function mapStateToPreps(state){
    
    
//     return {count:state}
// }

// // a函数 的返回值作为一个对象 里面有各种方法 操作状态的方法 传递给 UI组件
// function mapDispatchToProps(dispatch){
    
    
//     return {
    
    
//         jia:(number)=>{
    
    
//             dispatch(creIncAction(number))
//         },
//         jian:(number)=>{
    
    
//             dispatch(creDecAction(number))
//         }
//     }
// }

// //创建并暴露一个 Count的容器组件
// export default  connect(mapStateToPreps,mapDispatchToProps)(CountUI)

//简写方法
export default  connect(
    state => ({
    
    
      count:state.he,
      renSu:state.rens.length
    }),
    {
    
    
        jia:creIncAction,
        jian:creDecAction
    }
    )(Count)

2.3. Achieve data interoperability
2.3.1. Summarize all reducers
. This time we have two component reducers, but the createStore() method in the store can only pass in one reducer.
At this time, we need to summarize multiple reducers into one reducer. :

// combineReducers 如果要 redux 管理多个状态,请引入它
import {
    
     createStore,applyMiddleware,combineReducers } from 'redux'
//导入 redux-thunk,用于支持异步 action
import thunk from 'redux-thunk'

import countReducer from './reducers/count'
import personReducer from './reducers/person'

//汇总所有的 reducer 变为一个总的 reducer
const allReducer = combineReducers({
    
    
    he:countReducer, 
    rens:personReducer
})

export default createStore(allReducer,applyMiddleware(thunk))

CombineReducers() method introduction:
Pass in an object, choose any attribute name, and the value is the value of the state you want to manage.

2.3.2. Re-enter the entry file index.js/use Provider to wrap the App

const Root = ReactDOM.createRoot(document.getElementById('root'))

Root.render(
     //用 Provider 包裹 App,将 store 传递给 Provider。供App中所有容器组件使用其中的状态
     <Provider store={
    
    store}>
          <App />
     </Provider>
)

2.3.3. Using the state of other components
Where container components are exposed:

export default  connect(
    state => ({
    
    
      count:state.he,
      renSu:state.rens.length
    }),
    {
    
    
        jia:creIncAction,
        jian:creDecAction
    }
    )(Count)

The first parameter of the connect() method is a function. The function will pass in a state by default.
This state contains all the states we manage using redux. You can read it according to your own needs.
After reading, it will be stored in props.
Personal blog: study notes for the rest of my life

Guess you like

Origin blog.csdn.net/m0_63135041/article/details/130385792