React——react-redux

因为自己是Vue开发者,所以会以Vuex的角度来看React的状态管理实现,这样可以帮助自己理解。毕竟两者都是参照Flux来分别实现的。之前写过一篇Vuex的分享 Vue中状态管理——Vuex

说起 react-redux 就不得不先说 redux

Redux

  • redux 是一个数据设计架构,专注于状态管理,和 react 解耦
  • 单一状态,单向数据流

redux 中有4个核心概念,分别是: storestateactionreducer

其中:

  • store 指的是存储数据的仓库,我们的数据只有放在这里才可以被 redux 管理起来。 (和Vuex中的store没区别)
    Redux 提供了一个createStore来生成Store。其中createStore接收一个reducers
  • state 指的是初始化的数据,这里的初始化数据是可以有多个的。 (和Vuex中的state没却别)
  • action 指的是需要变化的数据,必须要有一个type参数和一些需要在state中修改的属性。(和Vuex中Mutation的payload参数一致,因为我们是在Mutation手动写好对应关系,所以不需要传递Type)。
  • reducer 因为 store 在收到我们传递过去的action之后需要对state进行更新,这个计算过程就叫做reducerreducer是一个函数,接受stateaction作为参数,返回一个新的state。(和Vuex中的Mutation一致)

看一下 React 的工作流程:

这里写图片描述

用户在view层通过 store.dispatch 来发送 action ,当 store 接收到用户传递过来的 action 后,会把 stateaction 传给 reducer ,而 reducer 会根据 action 的 type,来返回一个新的 state。而当 store 有变化的时候,store 就会调用监听函数 store.subscribe ,从而使得view层发生变化。

因为 Redux 是和 React 完全耦合的,所以我们需要使用 react-redux 来方便我们使用。

React-Redux

react-redux 提供了两个方法: connectProvider

Provider

这个方法是包裹在IApp外边,然后传递给其一个 store 这样所有其包裹的子组件都可以使用 store 上存储的数据了。
类似于这样:

import { Provider } from 'react-redux'
import { createStore } from 'redux'
import ReactDDM from 'react-dom'
import reducers from './reducers'

const store = createStore(reducers)
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

connect

这个其实类似于Vuex中的 mapMutaionmapGetter 。它接受2个参数,分别是: mapStateToPropsmapDispatchToProps

使用方法:

import { connect } from 'react-redux'

connect(mapStateToProps, mapDispatchToProps)(ClassName)

这里是很明显是一个装饰器,所以我们可以使用更优雅的写法。
使用一个 babel

yarn add babel-plugin-transform-decarators-legacy --save-dev

.babelrc文件
    "babel": {
        "plugins": ["transform-decarators-legacy"]
    }

这样就可以直接使用装饰器模式来进行构建

import { connect } from 'react-reudx'
import { changeUserName } from './redux'
@connect(
    state => state,
    { changeUserName  }
)

需要注意的是,mapStateToProps 接收一个state,返回一个对象。 mapDispatchToProps 接收一个 dispatch 组成的对象。

猜你喜欢

转载自blog.csdn.net/qq_35534823/article/details/80062915