redux

学习文档
  1. 英文文档: https://redux.js.org/
  2. 中文文档: http://www.redux.org.cn/
  3. Github: https://github.com/reactjs/redux

redux是什么?

  1. redux是一个独立专门用于做状态管理的JS库(不是react插件库)
  2. 它可以用在react, angular, vue等项目中, 但基本与react配合使用
  3. 作用: 集中式管理react应用中多个组件共享的状态

redux工作流程

在这里插入图片描述

什么情况下需要使用redux
  1. 总体原则: 能不用就不用, 如果不用比较吃力才考虑使用
  2. 某个组件的状态,需要共享
  3. 某个状态需要在任何地方都可以拿到
  4. 一个组件需要改变全局状态
  5. 一个组件需要改变另一个组件的状态
redux的核心API

createStore()

  1. 作用:
    创建包含指定reducer的store对象
  2. 编码:
import {createStore} from 'redux'
import counter from './reducers/counter'
const store = createStore(counter)

.store对象

  1. 作用:
    redux库最核心的管理对象
  2. 它内部维护着:
    state
    reducer
  3. 核心方法:
    getState()
    dispatch(action)
    subscribe(listener)
  4. 编码:
    store.getState()
    store.dispatch({type:‘INCREMENT’, number})
    store.subscribe(render)

. applyMiddleware()

  1. 作用:
    应用上基于redux的中间件(插件库)
  2. 编码:
import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'  // redux异步中间件
const store = createStore(
  counter,
  applyMiddleware(thunk) // 应用上异步中间件
)

combineReducers()

  1. 作用:
    合并多个reducer函数
  2. 编码:
export default combineReducers({
  user,
  chatUser,
  chat
})
redux的三个核心概念

. action

  1. 标识要执行行为的对象
  2. 包含2个方面的属性
    a. type: 标识属性, 值为字符串, 唯一, 必要属性
    b. xxx: 数据属性, 值类型任意, 可选属性
  3. 例子:
    const action = {
    type: ‘INCREMENT’,
    data: 2
    }
  4. Action Creator(创建Action的工厂函数)
    const increment = (number) => ({type: ‘INCREMENT’, data: number})

. reducer

  1. 根据老的state和action, 产生新的state的纯函数
  2. 样例
		export default function counter(state = 0, action) {
		  switch (action.type) {
		    case 'INCREMENT':
		      return state + action.data
		    case 'DECREMENT':
		      return state - action.data
		    default:
		      return state
		  }
		}
  1. 注意
    a. 返回一个新的状态
    b. 不要修改原来的状态

. store

  1. 将state,action与reducer联系在一起的对象
  2. 如何得到此对象?
    import {createStore} from ‘redux’
    import reducer from ‘./reducers’
    const store = createStore(reducer)
  3. 此对象的功能?
    getState(): 得到state
    dispatch(action): 分发action, 触发reducer调用, 产生新的state
    subscribe(listener): 注册监听, 当产生了新的state时, 自动调用

使用redux编写应用

下载依赖包
npm install --save redux
例子:
先选数值,再选加、减、奇数时加、异步加
第一行是的结果
在这里插入图片描述
代码目录:
在这里插入图片描述
redux/action-types.js

/*

  action对象的type常量名称模块

 */

  export const INCREMENT = 'increment'

  export const DECREMENT = 'decrement'

redux/actions.js

/*

action creator模块

 */

  import {INCREMENT, DECREMENT} from './action-types'

  

  export const increment = number => ({type: INCREMENT, number})

  export const decrement = number => ({type: DECREMENT, number})

redux/reducers.js

/*

  根据老的state和指定action, 处理返回一个新的state

 */

  

  import {INCREMENT, DECREMENT} from './action-types'

  

  export function counter(state = 0, action) {

  console.log('counter', state, action)

  switch (action.type) {

    case INCREMENT:

      return state + action.number

    case DECREMENT:

      return state - action.number

    default:

      return state

  }

}

components/app.jsx

/*

  应用组件

 */

  import React, {Component} from 'react'

  import PropTypes from 'prop-types'

  import * as actions from '../redux/actions'

  

  export default class App extends Component {

  

  static propTypes = {

    store: PropTypes.object.isRequired,

  }

  

  increment = () => {

    const number = this.refs.numSelect.value * 1

    this.props.store.dispatch(actions.increment(number))

  }

  

  decrement = () => {

    const number = this.refs.numSelect.value * 1

    this.props.store.dispatch(actions.decrement(number))

  }

  

  incrementIfOdd = () => {

    const number = this.refs.numSelect.value * 1

  

    let count = this.props.store.getState()

    if (count % 2 === 1) {

      this.props.store.dispatch(actions.increment(number))

    }

  }

  

  incrementAsync = () => {

    const number = this.refs.numSelect.value * 1

    setTimeout(() => {

      this.props.store.dispatch(actions.increment(number))

    }, 1000)

  }

  

  render() {

    return (

      <div>

        <p>

          click {this.props.store.getState()} times {' '}

        </p>

        <select ref="numSelect">

          <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}>increment if odd</button>

        {' '}

        <button onClick={this.incrementAsync}>increment async</button>

      </div>

    )

  }

}

index.js

import React from 'react'

  import ReactDOM from 'react-dom'

  import {createStore} from 'redux'

  

  import App from './components/app'

  import {counter} from './redux/reducers'

  

  // 根据counter函数创建store对象

  const store = createStore(counter)

  

  // 定义渲染根组件标签的函数

  const render = () => {

  ReactDOM.render(

    <App store={store}/>,

    document.getElementById('root')

  )

}

  // 初始化渲染

  render()

  

  // 注册(订阅)监听, 一旦状态发生改变, 自动重新渲染

  store.subscribe(render)
问题
  1. redux与react组件的代码耦合度太高
  2. 编码不够简洁
react-redux

. 理解

  1. 一个react插件库
  2. 专门用来简化react应用中使用redux
    React-Redux将所有组件分成两大类
  3. UI组件
    a. 只负责 UI 的呈现,不带有任何业务逻辑
    b. 通过props接收数据(一般数据和函数)
    c. 不使用任何 Redux 的 API
    d. 一般保存在components文件夹下
  4. 容器组件
    a. 负责管理数据和业务逻辑,不负责UI的呈现
    b. 使用 Redux 的 API
    c. 一般保存在containers文件夹下

相关API

  1. Provider
    让所有组件都可以得到state数据


  2. connect()
    用于包装 UI 组件生成容器组件
import { connect } from 'react-redux'
  connect(
    mapStateToprops,
    mapDispatchToProps
  )(Counter)
  1. mapStateToprops()
    将外部的数据(即state对象)转换为UI组件的标签属性
  const mapStateToprops = function (state) {
   return {
     value: state
   }
  }
  1. mapDispatchToProps()
    将分发action的函数转换为UI组件的标签属性
    简洁语法可以直接指定为actions对象或包含多个action方法的对象

使用react-redux

  1. 下载依赖包
    npm install --save react-redux

目录
在这里插入图片描述
2) redux/action-types.js
不变
3) redux/actions.js
不变
4) redux/reducers.js
不变
5) components/counter.jsx

/*

UI组件: 不包含任何redux API

 */

  import React from 'react'

  import PropTypes from 'prop-types'

  

  export default class Counter extends React.Component {

  

  static propTypes = {

    count: PropTypes.number.isRequired,

    increment: PropTypes.func.isRequired,

    decrement: PropTypes.func.isRequired

  }

  

  increment = () => {

    const number = this.refs.numSelect.value * 1

    this.props.increment(number)

  }

  

  decrement = () => {

    const number = this.refs.numSelect.value * 1

    this.props.decrement(number)

  }

  

  incrementIfOdd = () => {

    const number = this.refs.numSelect.value * 1

    let count = this.props.count

    if (count % 2 === 1) {

      this.props.increment(number)

    }

  }

  

  incrementAsync = () => {

    const number = this.refs.numSelect.value * 1

    setTimeout(() => {

      this.props.increment(number)

    }, 1000)

  }

  

  render() {

    return (

      <div>

        <p>

          click {this.props.count} times {' '}

        </p>

        <select ref="numSelect">

          <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}>increment if odd</button>

        {' '}

        <button onClick={this.incrementAsync}>increment async</button>

      </div>

    )

  }

}
  1. containters/app.jsx
/*

  包含Counter组件的容器组件

 */

  import React from 'react'

  // 引入连接函数

  import {connect} from 'react-redux'

  // 引入action函数

  import {increment, decrement} from '../redux/actions'

  

  import Counter from '../components/counter'

  

  // 向外暴露连接App组件的包装组件

  export default connect(

  state => ({count: state}),

  {increment, decrement}

)(Counter)
  1. index.js
import React from 'react'

  import ReactDOM from 'react-dom'

  import {createStore} from 'redux'

  import {Provider} from 'react-redux'

  

  import App from './containers/app'

  import {counter} from './redux/reducers'

  

  // 根据counter函数创建store对象

  const store = createStore(counter)

  

  // 定义渲染根组件标签的函数

  ReactDOM.render(

  (

    <Provider store={store}>

      <App />

    </Provider>

  ),

  document.getElementById('root')

store.js

import React from 'react'
import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
import {composeWithDevTools} from 'redux-devtools-extension'

import reducers from './reducers'

// 根据counter函数创建store对象
export default createStore(
  reducers,
  composeWithDevTools(applyMiddleware(thunk)) // 应用上异步中间件
)
问题
  1. redux默认是不能进行异步处理的,
  2. 应用中又需要在redux中执行异步任务(ajax, 定时器)
redux异步编程

下载redux插件(异步中间件)
npm install --save redux-thunk

目录
在这里插入图片描述
reducers.js

import {combineReducers} from 'redux'
import {
  INCREMENT,
  DECREMENT
} from './action-types'

function counter(state = 0, action) {
  console.log('counter', state, action)
  switch (action.type) {
    case INCREMENT:
      return state + action.number
    case DECREMENT:
      return state - action.number
    default:
      return state
  }
}

export default combineReducers({
  counter
})

index.js

import {createStore, applyMiddleware} from 'redux'

  import thunk from 'redux-thunk'

  // 根据counter函数创建store对象

  const store = createStore(

  counter,

  applyMiddleware(thunk) // 应用上异步中间件

  )

redux/actions.js

// 异步action creator(返回一个函数)

 export const incrementAsync = number => {

 return dispatch => {

   setTimeout(() => {

     dispatch(increment(number))

   }, 1000)

 }

}

components/counter.jsx

incrementAsync = () => {

  const number = this.refs.numSelect.value*1

  this.props.incrementAsync(number)

}

containers/app.jsx

import {increment, decrement, incrementAsync} from '../redux/actions'
// 向外暴露连接App组件的包装组件
export default connect(
  state => ({count: state}),
  {increment, decrement, incrementAsync}
)(Counter)

使用上redux调试工具

安装chrome浏览器插件

下载工具依赖包
npm install --save-dev redux-devtools-extension
. 编码

import { composeWithDevTools } from 'redux-devtools-extension'


  const store = createStore(

  counter,

  composeWithDevTools(applyMiddleware(thunk)) 

  )

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值