Redux介绍

141 阅读2分钟

Redux中文文档

Vuex用法

Vuex参考文档

Redux的API

createStore(reducer, [preloadedState], enhancer)

创建一个 Redux store 来以存放应用中所有的state 应用中应有且仅有一个store

  • reducer(Function):接收两个参数,分别是当前的 state 树和要处理的 action ,返回新的 state 树
  • [preloadedState] (any) 可选,不常用 文档
  • enhancer(Function),跟中间件差不多(也是应用其他redux插件的地方),通过复合函数改变store接口,返回一个新的强化过的 store creator
import { createStore } from 'redux'

function reducer(state = [], action) {
  return state
}

const store = createStore(reducer)

export default store

更多应用

  • 有且仅有一个store,但可以创建多个reducer,然后通过combineReducers把多个reducer创建成一个根reducer
  • state的格式可以是普通的对象,也可以使用Immutable这类实现安全性较高

Store

改变store内state的唯一途径是对它dispatch一个action Store不是类。它只是仅有几个方法的对象,要创建它,只需要把根部的reducing函数传给createStore

  • getState() 返回应用中的state,但不是最新的
  • dispatch(action) 分发action,这是触发state变化的唯一途径,其中action仅为一个普通对象
  • subscribe(listener) 当有dispatch执行的时候就会执行
import React from 'react'
// 导入store
import store from './../../store'
// 导入action
// import {
//   setActionA,
//   setActionB
// } from './../../store/actionCreators'
class ReduxExample extends React.Component {
  constructor(props) {
    super(props)
    this.state = store.getState()
    
    // subscribe监听store中的数据是否发生变化
    this.handleStoreChange = this.handleStoreChange.bind(this)
    store.subscribe(this.handleStoreChange);
  }
  render() {
    return (
      <div>
        <h2>redux-example</h2>
        <div>
          {this.state.valueA}
        </div>
      </div>
    )
  }
  componentDidMount() {
    console.log(store.getState())
    setTimeout(() => {
      store.dispatch({
        type: 'A',
        value: 'A'
      })
      console.log(this.state)
      console.log(store.getState())
    }, 1000)
  }
  handleStoreChange() {
    // 重新获取store中的state
    this.setState(store.getState())
  }
}
export default ReduxExample

  • replaceReducer(nextReducer)

combineReducers

把多个reducer创建成一个根reducer,跟Vuex的modules很像

applyMiddleware

用来应用其他插件

bindActionCreators

参考文档 用来让组件更好的获取action

compose

当有多个增强器,也就是多个插件一起使用的时候,可以用compose函数包裹

react-redux

组件中更好的应用store,可以更加方便规范的获取store中state树和dispatch

  • <Provider store>
  • <Provider store> 使组件层级中的 connect() 方法都能够获得 Redux store。正常情况下,你的根组件应该嵌套在 <Provider> 中才能使用 connect() 方法。
  • connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])