redux基础

1. 什么是Redux ?

Redux 是JavaScript状态容器, 提供了预测的状态管理,.

可以让你构建一致化的应用, 应用于 不同的环境( 客户端, 服务器, 元素应用)

2. Action

Action是把数据从应用, 传到Stroe的有效载荷.他是Stroe的唯一来源, 一般来是你会通过troe.dispath将action传到 stroe中

action相当于一个触发器, 只有当我们触发了action, 我们才能对state状态的更新,它定义了我们触发事件的类型和行为.本质就是一个描述了发生了什么的的 普通对象

Action 本质上是 JavaScript 普通对象。我们约定,action 内必须使用一个字符串类型的 type 字段来表示将要执行的动作。action 还需要添加一个index来表示 用户完成任务的动作序列号.因为事件是存放在数组中的, 所以我们通过下标index 来引用特定的任务.

 export  function handleIncrement(index){
    return{
        type:'increment',
        index,
    }
}
export function  handleDecrement(index){
    return {
        type:'decrement',
        index,
    }
}

我们通常将action 定义成一个独立的js文件,降低代码的耦合性, 便于管理和维护.

3. Reducer

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

reducer就是一个纯函数, 接受旧的state和action. 返回 新的state

(previousState, state) => new State

永远不要在 reduce里做这些操作

  • 传入修改参数
  • 执行有副作用的操作, 如API的请求和路由跳转
  • 调用非纯函数, 如 Date.now() 或Math.random()

Redux 首次执行时, state为undefined , 此时我们可以借机设置并返回应用初始的state

下面是一个简单的reducer案列

const initState = { //初始的state数据
    count:0,
}
export default function reducer(state = initState, action){//使用es6的参数默认值来给state设置一个初始值
    switch (action.type) {
        case 'increment':
            return  Object.assign({},state,{
                count:++state.count 
            })
            break;
        case 'decrement':
            return  Object.assign({},state,{
                count:--state.count
            })
        default:
            return state;
    }
}

每个reducer只负责管理全局的state中它赋值的一部分.每一个reducer的state参数都不同, 分别对应它管理的那部分state数据

4. Store

Stroe就是一个数据仓库对象,Store有以下职责:

  • 维持应用的state
  • 提供getState()方法获取state;
  • 提供 dispath(action)方法更新state;
  • 通过subscribe(listener)方法注册监听器
  • 通过subscribe(listener) 返回的函数注销监听器

Redux应用只有单一的Store.当需要拆分数据处理逻辑时, 你应该使用reducer组合,而不是创建多个store.

我们可以创建一个单独的store.js文件, 来创建一个 仓库

import {createStore} from "redux";
import reducer from "./reducer"
export default createStore(reducer)

接下来我们在 App.js中使用

import React, { Component } from 'react';
import './App.css'
import storeOne from "./Redux1/store"

import { handleIncrement, handleDecrement } from "./Redux1/Action"

class App extends Component {
  add = () => {

    storeOne.dispatch(handleIncrement())
    // 监听state数据的变化
    const unSubscribe = storeOne.subscribe(() => {   // ,每次 state更新时 打印日志 即触发这个回调函数, 返回 一个注销监听器
      this.setState({})
      console.log('正在监听');
    })
    unSubscribe()// 解除监听
  }
  sub = () => {
    storeOne.dispatch(handleDecrement())
  }
  render() {
    let { count } = storeOne.getState()
    return (
      
{count} {/* // 注册一个点击事件 */}
); } } export default App;

你可能感兴趣的:(redux基础)