Redux 关于mapStateToProps和mapDispatchToProps解析

”只有遇到 React 实在解决不了的问题,你才需要 Redux“

Redux应用的三大原则
  • 单一数据源 State是只读的 Reducer必须是一个纯函数
  • store就是保存数据的地方,你可以把它看成一个数据,整个应用只能有一个store
  • Redux提供createStore这个函数,用来生成Store
//store.js
import { createStore, combineReducers, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'//实现异步action的中间件
//引入不同模块的reducers
import * as custObj from './custObj/reducers'
import * as orderObj from './orderObj/reducers'
 
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
//createStore这个函数,用来生成Store
const store = createStore(
  combineReducers({
    ...custObj,
    ...orderObj
  }),//把一个由多个不同 reducer 函数作为 value 的 object,合并成一个最终的 reducer 函数
  composeEnhancers(applyMiddleware(thunk))
)
 
export default store
state的改变会导致View的变化,但是在redux中不能直接操作state,也就是说不能使用setState来操作,用户只能接触到View。
 
mapStateToProps和mapDispatchToProps
React-Redux 提供connect方法,用于从 UI 组件生成容器组件
connect方法接受两个参数:mapStateToPropsmapDispatchToProps
前者负责输入逻辑,即将state映射到 UI 组件的参数(props),后者负责输出逻辑,即将用户对 UI 组件的操作映射成 Action。
 
一个完整的redux状态管理还要有reducer和对应的action. 
首先引入connect和相应的action。然后是mapStateToProps和mapDispatchToProps 函数。
mapStateToProps函数,接受store state然后返回所需的数据对象。每个数据通过state.xx的方式,从reducer里获取值映射到props.
先在action里面获取对应的方法 然后在mapDispatchToProps进行dispatch, action根据方法名返回action type,再到reducer返回对应value。
import { connect } from 'react-redux'
import { setCustId } from '@/redux/custObj/actions'
js
function mapStateToProps (state) {
  return {
    custId: state.custId
  }
}

function mapDispatchToProps (dispatch) {
  return {
    setCustId: (val) => {//传给props的方法名
      dispatch(setCustId(val))//action里面的方法名
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(OrderDetail)
action
// 接收返回的cusntId
//Action是一个对象其中type属性是必须的,表示Action的名称

export const setCustId= (value) => {
  return {
    type: type.SET_CUST_ID,
    custId: value
  }
}
reducer
//Store收到Action以后,必须给出一个新的state,这样view才会发生变化
//Reducer是一个纯函数,他接收Action和当前state作为参数,返回一个新的state
export const custId= (state = '', action) => {
  switch (action.type) {
    case type.SET_CUST_ID:
      return action.custId
    default:
      return state
  }
}
原文地址:https://www.cnblogs.com/hl-tyc/p/14237473.html