React中redux相关使用

155 阅读4分钟

一、Redux工作流程

//安装
npm install --save redux

  • View在redux中会派发action方法
  • action通过store的dispatch方法会派发给store
  • store接收action,连同之前的state,一起传递给reducer
  • reducer返回新的数据给store
  • store去改变自己的state

Store

store就是redux的一个数据中心,简单的理解就是我们所有的数据都会存放在里面,然后在界面上使用时,从中取出对应的数据。因此最开始,我们要创建一个这样的store,redux提供了createStore方法。

  • createStore 可以帮助我们创建一个store
  • store.dispatch 帮助我们派发action 这个action会传递给store
  • store.getState 获取到store里面所有的数据内容
  • store.subscribe 可以让我们订阅(监听) store的改变 只要store发生改变, 这个方法的回调函数就会执行

Action

Action 是把数据从应用传到 store 的有效载荷。它是 store 数据的唯一来源。一般来说你会通过 store.dispatch() 将 action 传到 store。

Reducer

Reducers 指定了应用状态的变化如何响应 actions 并发送到 store 的,记住 actions 只是描述了有事情发生了这一事实,并没有描述应用如何更新 state。

----代码演示----
下面是我自己写的一个案例供参考:

image.png

image.png

image.png

图1:

import {createStore} from 'redux'//引入redux
import reducer from './reducer'//引入同文件下的reducer

const store=createStore(reducer)

export default store

图2:

// 公共数据
const defaultState={
    inputValue:'',
    list:[
        {id:0,name:'苹果'},
        {id:1,name:'草莓'}
    ]
}

// 修改defaultState里的逻辑
const reducer=(state=defaultState,action)=>{//监听input框内容 
    console.log(action)
    if(action.type==='input_value_change'){
        let newState=JSON.parse(JSON.stringify(state))
        newState.inputValue=action.value
        return newState
    }
    if(action.type==='add_item_value'){//添加
        let newState=JSON.parse(JSON.stringify(state))
        newState.list.push(action.value)
        newState.inputValue=''//input框置空
        return newState
    }
    if(action.type==='delete_item_value'){//删除  
        let newState=JSON.parse(JSON.stringify(state))
        newState.list.splice(action.value,1)
        return newState
    }

    return state
}

export default reducer

图3:

import React, { Component } from 'react'
// 引入redux数据库
import store from './redux'

class App extends Component {
  constructor(props){
    super(props)
    this.state=store.getState()//redux数据赋值给state
  }

  // redux里面的值发生改变后我们需要这两个步骤来触发视图的更新
  componentDidMount(){
    store.subscribe(this.handleStoreChange)
  }
  handleStoreChange=()=>{
    this.setState(store.getState())
  }

  inputChange=(e)=>{//监听input框内容 
   let action={
     type:'input_value_change',
     value:e.target.value
   }
   store.dispatch(action)
  }

  addFruits=()=>{//添加
    let action={
      type:'add_item_value',
      value:{id:this.state.list.length+1,name:this.state.inputValue}
    }
    store.dispatch(action)
  }

  deleteFruits=(index)=>{//删除  
    let action={
      type:'delete_item_value',
      value:index
    }
    store.dispatch(action)
  }
  render() {
    return (
      <div>
        {/* 这个用的只是 redux */}
          <input value={this.state.inputValue} onChange={this.inputChange}/>
          <button onClick={this.addFruits}>添加</button>
          <ul>
              {this.state.list.map((item,index)=><li key={item.id}>{item.name} <button onClick={()=>this.deleteFruits(index)}>删除</button></li>)}
              
          </ul>
      </div>
    )
  }
}

export default App

二、React-redux工作流程

//安装
npm install --save react-redux
React-Redux 将所有组件分成两大类:UI 组件(presentational component)和容器组件(container component)。

UI 组件有以下几个特征:

  • 只负责 UI 的呈现,不带有任何业务逻辑
  • 没有状态(即不使用this.state这个变量)
  • 所有数据都由参数(this.props)提供
  • 不使用任何 Redux 的 API 容器组件的特征恰恰相反
  • 负责管理数据和业务逻辑,不负责 UI 的呈现
  • 带有内部状态
  • 使用 Redux 的 API

总之,只要记住一句话就可以了:
UI 组件负责 UI 的呈现,容器组件负责管理数据和逻辑。

Connect

connect()是react-redux中的核心方法之一,用于从 UI 组件生成容器组件,它将react组件预redux中的Store真正连接在一起。

connect 方法接受两个参数:mapStateToPropsmapDispatchToProps。它们定义了 UI 组件的业务逻辑。前者负责输入逻辑,即将 state 映射到 UI 组件的参数 props,后者负责输出逻辑,即将用户对 UI 组件的操作映射成 Action

Provider 组件

connect方法生成容器组件以后,需要让容器组件拿到state对象,才能生成 UI 组件的参数。

一种解决方法是将state对象作为参数,传入容器组件。但是,这样做比较麻烦,尤其是容器组件可能在很深的层级,一级级将state传下去就很麻烦。

React-Redux 提供Provider组件,可以让容器组件拿到state

mapStateToProps

<1>mapStateToProps 是一个函数,它接受 state 作为参数,返回一个对象。这个对象有一个 todos 属性,代表 UI 组件的同名参数,后面的 getVisibleTodos 也是一个函数,可以从 state 算出 todos 的值。
mapStateToProps 建立一个从(外部的)state 对象到(UI 组件的)props 对象的映射关系。执行后应该返回一个对象,里面的每一个键值对就是一个映射。

mapDispatchToProps

<2> mapDispatchToProps 用来建立 UI 组件的参数到 store.dispatch 方法的映射。它定义了哪些用户的操作应该当作 Action,传给 Store。它可以是一个函数,也可以是一个对象。

  • 是函数则会得到 dispatchownProps(容器组件的 props 对象)两个参数。
  • 是一个对象,它的每个键名也是对应 UI 组件的同名参数,键值应该是一个函数,会被当作 Action creator ,返回的 Action 会由 Redux 自动发出。

----代码演示----
react-redux和上面的redux一样的内容有 (底下图片内容) image.png

index.js中使用Provider包括App 并写上数据库store

image.png

在页面中 引入connect 来包括 image.png

this.state 改为 this.props image.png

属性mapStateToProps,方法mapDispatchToProps
image.png

三、两者区别

1、 redux是react中进行state状态管理的JS库(并不是react插件),一般是管理多个组件中共享数据状态。这个是和Vuex是一样的 **

2、 React-Redux是Redux的官方React绑定库。它能够使你的React组件从Redux store中读取数据,并且向store分发actions以更新数据。 **