在react中使用redux

redux是什么?

  1. redux是一个独立专门用于做状态管理的JS库(不是react插件库)
  2. 它可以用在react,angular,vue等项目中,但基本与react配合使用
  3. 作用:集中式管理react应用中的多个组件共享的状态
    redux工作流程:
    在这里插入图片描述什么情况下需要使用redux
  4. 总体原则:能不用就不用
  5. 某个组件的状态需要共享
  6. 某个状态需要在任何地方都可以拿到
  7. 一个组件需要改变全局状态
  8. 一个组件需要改变另一个组件的状态

redux的核心API

createStore()

作用:创建包含指定reducer的对象
编码:

import {createStore} from 'redux'
import counter from './reducers/counter'
const store = createStore(counter)

store对象:

作用:redux库最核心的管理对象
它的内部维护着:state,reducer
核心方法:
getState()
dispatch(action)
subscribe(listener)

编码:

 store.getState()
store.dispatch({type:'INCREMENT', number})
store.subscribe(render)

applyMiddleware()

作用:应用上基于redux的中间件(插件库)
编码:

import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'  // redux异步中间件
const store = createStore(
  counter,
  applyMiddleware(thunk) // 应用上异步中间件
)

combineReducers()

作用:合并多个reducer函数
编码:

export default combineReducers({
  user,
  chatUser,
  chat
})

redux的三个核心概念

action

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

reducer:

根据旧的state和action, 产生新的state的纯函数
样例

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
		  }
		}

注意:返回一个新的状态,不要修改原来的状态

store:

将state,action与reducer联系在一起的对象
得到此对象:

        import {createStore} from 'redux'
		import reducer from './reducers'
		const store = createStore(reducer)

此对象的功能:
getState(): 得到state
dispatch(action): 分发action, 触发reducer调用, 产生新的state
subscribe(listener): 注册监听, 当产生了新的state时, 自动调用

使用redux编写应用:

下载依赖包:

npm install --save redux

redux/action-type.js

/*
Action对象的type常量名称模块
 */
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'

redux/action.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
  }
}

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)

components/App.js
首先需要下载 props-types依赖包

npm install --save props-types
/*
应用组件
 */
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>
    )
  }
}

问题:redux与react组件的代码耦合度太高,编码不够简洁

react-reudx

一个react插件库,专门用来简化react应用中使用redux

将所有组件分为两大类:
UI组件:

  • 只负责UI的呈现,不带有任何业务逻辑

  • 通过props接受数据(一般数据和函数)

  • 不使用任何redux的API

  • 一般保存在components文件夹中

  • List item

容器组件:

负责管理数据和业务逻辑,不负责UI呈现

  • 使用redux的API
  • 一般保存在containers文件夹下

相关的API:

Provider:

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

<Provider store={store}>
      <App/>
    </Provider>

connect():

用于包装UI组件生成容器组件(将组件与react-redux连接起来)

import {connect} from 'react-redux'
//引入action函数
connect(
  mapStateToProps,//映射状态成为属性,是一个函数返回的是一个对象
  mapDispatchToProps,//是一个对象,返回的是一个action方法。最终会转化为dispatch调用的一个函数
)(Counter)

mapStateToprops()

将外部的数据(即state对象)转换为UI组件的标签属性

const mapStateToprops = function (state) {
  return {
    value: state
  }
}

mapDispatchToProps()

将分发action的函数转换为UI组件的标签属性
简洁语法可以直接指定为actions对象或包含多个action方法

使用react-redux

1,npm install --save react-redux
2,redux/action-types.js不变
3,redux/action.js不变
4,redux/reducers.js不变
5,containers/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)

6,components/Counter.jsx

/*
应用组件
 */
import React, {Component} from 'react'
import PropTypes from 'prop-types'
// import * as actions from '../redux/actions'

export default class Counter extends Component {

  static propTypes = {
    // store: PropTypes.object.isRequired,
    count: PropTypes.number.isRequired,
    increment: PropTypes.func.isRequired,
    decrement: PropTypes.func.isRequired
  }

  increment = () => {
    const number = this.refs.numSelect.value * 1
    // this.props.store.dispatch(actions.increment(number))
    this.props.increment(number)
  }

  decrement = () => {
    const number = this.refs.numSelect.value * 1
    // this.props.store.dispatch(actions.decrement(number))
    this.props.decrement(number)
  }

  incrementIfOdd = () => {
    const number = this.refs.numSelect.value * 1

    // let count = this.props.store.getState()
    let count = this.props.count
    if (count % 2 === 1) {
      // this.props.store.dispatch(actions.increment(number))
      this.props.increment(number)
    }
  }

  incrementAsync = () => {
    const number = this.refs.numSelect.value * 1
    setTimeout(() => {
      // this.props.store.dispatch(actions.increment(number))
      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>
    )
  }
}
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐