Redux(一):基本用法

471 阅读2分钟

1、介绍

为了有更好的state管理,就需要一个库来作为更专业的顶层state分发给所有React应用,这就是Redux。



Redux 用来确保state变化的可预测性,主要的约束有:

1、state以单一对象存储在store对象中

2、state只读

3、使用纯函数reducer 执行state更新

state为单一对象,Redux只需要维护一棵状态树,服务端很容易初始化状态,易于服务器渲染。state通过dispatch(action)来触发更新,更新逻辑由reducer执行。


Redux的三个基本概念:Action、Reducer、Store

1、action 是纯声明式的数据结构,可以理解为应用向store传递的数据信息。

export const getUserDataDone = userData => ({
  payload: userData,
  type: GET_USERINFO_SUCCESS,
});

2、reducer 是一个纯函数,(previousState, action) => newState。根据相关action的数据进行逻辑处理,修改store中的状态。

3、store

store是一个单一对象:

  • 管理应用的state
  • 通过 store.getState()可以获取state
  • 通过store.dispatch(action)触发state更新
  • 通过store.subscribe(listener) 注册监听器

产生一个 Store:

import { createStore } from 'redux'

//这里的 Reducer 就是刚才的 Reducer 函数
let store = createStore(Reducer);

通过 dispatch 一个 action 来让它改变状态
store.dispatch( changeText() );

store.getState(); // { text : 'Hello Stark' }

Redux 和 React 是没有必然关系的,Redux 用于管理 state,与具体的 View 框架无关。不过,Redux 特别适合那些 state => UI 的框架(比如:React, Deku)。

可以使用 react-redux 来绑定 React.

1、首先在最外层容器中,所有内容包裹在Provider组件中,将之前创建的store作为prop 传给Provider。

return Component => (
      <Provider store={store}>{Component}</Provider>
  );

2、connect是重点,接受两个参数(数据绑定mapStateToProps和事件绑定mapDispatchToProps),再接受一个参数(要绑定的组建本身)。

mapStateToProps:构建好Redux系统的时候,会被自动初始化,但是你的React组件并不知道它的存在,因此你需要分拣出你需要的Redux状态,所以你需要绑定一个函数,它的参数是state,简单返回你关心的几个值。将state作为props绑定到组件上。


const mapStateToProps = (state, ownProps) => {
  return {
    active: ownProps.filter === state.visibilityFilter
  }
}


mapDispatchToProps是可选的:将 action 作为 props 绑定到组件上。如果不传这个参数redux会简单把dispatch作为属性注入给组件,可以手动当做store.dispatch使用。


const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    increase: (...args) => dispatch(actions.increase(...args)),
    decrease: (...args) => dispatch(actions.decrease(...args))
  }
}


参考:

https://www.zhihu.com/question/41312576?sort=created

http://www.imweb.io/topic/5a426d32a192c3b460fce354