简介

  • Redux 是一个有用的架构
  • Redux 的适用场景:多交互、多数据源

工作流程图

action

用户请求

//发出一个action
import { createStore } from 'redux';
const store = createStore(fn);

//其中的type属性是必须的,表示 Action 的名称。其他属性可以自由设置
const action = {
  type: 'ADD_TODO',
  data: 'Learn Redux'
};

store.dispatch(action);

Reducer

状态机
Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。
Reducer 是纯函数,就可以保证同样的State,必定得到同样的 View。但也正因为这一点,Reducer 函数里面不能改变 State,必须返回一个全新的对象

const defaultState = 0;
const reducer = (state = defaultState, action) => {
  switch (action.type) {
    case 'ADD':
      return {
          ...state,
          data: action.data
      }
    default:
      return state;
  }
};
Recucer的拆分
//index
import {combineReducers} from 'redux';
import proIndex from './proIndex';
import product from './product'
export default combineReducers({
    proIndex,
    product,
});

//product
import actions from '../action/index'
import {getDocMenu} from "../action/user/product";

const {
    GET_PRODUCT_DOCUMENT_SUCCESS
} = actions;

export default (state = {},action) =>{
    switch (action.type) {
        case GET_PRODUCT_DOCUMENT_SUCCESS:
            return{
                ...state,
                getDocMenu: action.data,
            }
        default:
            return state;
    }
}

//proIndex
import actions from '../action/index';

const {
    GET_SERVICE_CLASSIFICATION_SUCCESS,
    GET_SERVICE_SUBJECT_SUCCESS,
} = actions;

export default (state = {},action) => {
    switch (action.type) {
        case GET_SERVICE_CLASSIFICATION_SUCCESS:
            return {
                ...state,
                getServiceClass: action.data,
            };
        case GET_SERVICE_SUBJECT_SUCCESS:
            return {
                ...state,
                getServiceSubject: action.data,
            };
        default:
            return state;
    }
};

store

数据仓库

import { createStore } from 'redux'
import todoApp from './reducers'
//创建store仓库
const store = createStore(todoApp)
//createStore方法还可以接受第二个参数(),表示 State 的最初状态。这通常是服务器给出的(window.STATE_FROM_SERVER就是整个应用的状态初始值)
const store = createStore(todoApp, window.STATE_FROM_SERVER)

//引入action
import {
  addTodo,
  toggleTodo,
  setVisibilityFilter,
  VisibilityFilters
} from './actions'

//打印当前状态
console.log(store.getState())

// 订阅state变化
// subscribe()方法返回一个函数用于取消监听
const unsubscribe = store.subscribe(() => console.log(store.getState()))

// 发出一些action
store.dispatch(addTodo('Learn about actions'))
store.dispatch(addTodo('Learn about reducers'))
store.dispatch(addTodo('Learn about store'))
store.dispatch(toggleTodo(0))
store.dispatch(toggleTodo(1))
store.dispatch(setVisibilityFilter(VisibilityFilters.SHOW_COMPLETED))

//取消监听状态更新
unsubscribe()

配置中间件

import { createStore } from 'redux'
import reducer from '../reducer/index'
import thunk from 'redux-thunk'
import promise from 'redux-promise'
import logger from 'redux-logger'

const store = createStore(
  reducer,
  applyMiddleware(thunk, promise, logger)
);

redux-thunk

store.dispatch()只能传入一个action对象,redux-thunk中间件则将其扩展为一个方法

//配置
import { createStore } from 'redux'
import reducer from '../reducer/index'
import thunk from 'redux-thunk'

const store = createStore(
  reducer,
  applyMiddleware(thunk)
);

//使用
export function getDocMenu(query='') {
    return async(dispatch) => {
        try {
            const data = (await axios(`${baseUrl}doc.do?${Qs.stringify(query)}`)).data;
            //这里的dispatch相当于store.dispatch
            dispatch({
                type: GET_PRODUCT_DOCUMENT_SUCCESS,
                data: data
            })
        }
        catch(error){
            dispatch({
                type: GET_PRODUCT_DOCUMENT_FAILURE,
                error: new Error('获取文档菜单失败')
            })
        }
    }
}

redux-saga

解决异步的另一种方法

//配置
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'

import reducer from './reducers'
import mySaga from './sagas'

// create the saga middleware
const sagaMiddleware = createSagaMiddleware()
// mount it on the Store
const store = createStore(
  reducer,
  applyMiddleware(sagaMiddleware)
)

// then run the saga
sagaMiddleware.run(mySaga)

//使用
// action creators
export function GET_USERS(users) {
    return { type: RECEIVE_USERS, data }
}

export function GET_ERROR(error) {
    return { type: FETCH_USERS_ERROR, data }
}

export function Begin_GET_POSTS() {
    return { type: BEGIN_GET_POSTS }
}

//saga.js
import { takeEvery } from 'redux-saga';
import { call, put } from 'redux-saga/effects';
import axios from 'axios';
import { BEGIN_GET_POSTS, GET_POSTS, GET_POSTS_ERROR } from '../reducers';

// worker saga
function* showPostsAsync(action) {
    try {
        const response = yield call(axios.get, 'https://jsonplaceholder.typicode.com/posts');
        yield put({
            type: GET_POSTS,
            data: response.data
        });
    } catch(e) {
        yield put({
            type: GET_ERROR,
            error: new Error('some error')
        });
    }
}

// wacther saga
function* watchGetPosts() {
    yield takeEvery(BEGIN_GET_POSTS, showPostsAsync);
}

// root saga
export default function* rootSaga() {
    yield watchGetPosts()
} 

//user.js

componentWillMount() {
    this.props.dispatch(Begin_GET_POSTS());
}

Redux概览的更多相关文章

  1. 【原】整理的react相关的一些学习地址,包括 react-router、redux、webpack、flux

    因为平时经常去网上找react相关的一些地址,找来找去很麻烦,所以自己整理了一下,不过前面部分不是我整理的, 是出自于:http://www.cnblogs.com/aaronjs/p/4333925 ...

  2. React Redux学习笔记

    React Router React Router 使用教程 Redux中间件middleware [译]深入浅出Redux中间件 Redux学习之一:何为middleware? ES6 ES6新特性 ...

  3. Redux系列x:源码解析

    写在前面 redux的源码很简洁,除了applyMiddleware比较绕难以理解外,大部分还是 这里假设读者对redux有一定了解,就不科普redux的概念和API啥的啦,这部分建议直接看官方文档. ...

  4. React Hooks实现异步请求实例—useReducer、useContext和useEffect代替Redux方案

    本文是学习了2018年新鲜出炉的React Hooks提案之后,针对异步请求数据写的一个案例.注意,本文假设了:1.你已经初步了解hooks的含义了,如果不了解还请移步官方文档.(其实有过翻译的想法, ...

  5. RxJS + Redux + React = Amazing!(译一)

    今天,我将Youtube上的<RxJS + Redux + React = Amazing!>翻译(+机译)了下来,以供国内的同学学习,英文听力好的同学可以直接看原版视频: https:/ ...

  6. 通过一个demo了解Redux

    TodoList小demo 效果展示 项目地址 (单向)数据流 数据流是我们的行为与响应的抽象:使用数据流能帮我们明确了行为对应的响应,这和react的状态可预测的思想是不谋而合的. 常见的数据流框架 ...

  7. RxJS + Redux + React = Amazing!(译二)

    今天,我将Youtube上的<RxJS + Redux + React = Amazing!>的后半部分翻译(+机译)了下来,以供国内的同学学习,英文听力好的同学可以直接看原版视频: ht ...

  8. redux学习

    redux学习: 1.应用只有一个store,用于保存整个应用的所有的状态数据信息,即state,一个state对应一个页面的所需信息 注意:他只负责保存state,接收action, 从store. ...

  9. webpack+react+redux+es6开发模式

    一.预备知识 node, npm, react, redux, es6, webpack 二.学习资源 ECMAScript 6入门 React和Redux的连接react-redux Redux 入 ...

随机推荐

  1. ElasticStack学习(十):深入ElasticSearch搜索之QueryFiltering、多/单字符串的多字段查询

    一.复合查询 1.在ElasticSearch中,有Query和Filter两种不同的Context.Query Context进行了相关性算分,Filter Context不需要进行算分,同时可以利 ...

  2. 利用Github Pages创建的Jekyll模板个人博客添加阅读量统计功能

    目录 前言 准备工作 模板文件修改 写在最后 内容转载自我自己的博客 @(文章目录) 前言 Jekyll 是一个简单的免费的 Blog 生成工具,类似 WordPress .它只是一个生成静态网页的工 ...

  3. C语言中的“>>”和“

    先说左移,左移就是把一个数的所有位都向左移动若干位,在C中用<<运算符.例如: int i = 1; i = i << 2; //把i里的值左移2位 也就是说,1的2进制是00 ...

  4. PHP-- B/S结构

    B/S结构(Browser/Server,浏览器/服务器模式),是WEB兴起后的一种网络结构模式,WEB浏览器是客户端最主要的应用软件.这种模式统一了客户端,将系统功能实现的核心部分集中到服务器上,简 ...

  5. jsp数据交互(一).3

    引入的文件如果是jsp则应定义为***.jspf文件,如果其他文件可定义为***.inc文件,即include file. jsp:include是既可以静态包含又可以动态包含,用jsp:includ ...

  6. context创建过程解析(三)之deployDirectories

    HostConfig.deployApps() //在监听到start事件类型,也就是StandardHost调用startInternal protected void deployApps() { ...

  7. 2019前端面试系列——Vue面试题

    Vue 双向绑定原理        mvvm 双向绑定,采用数据劫持结合发布者-订阅者模式的方式,通过 Object.defineProperty()来劫持各个属性的 setter.getter,在数 ...

  8. 关于STM32F103+ESP8266+阿里云过程之修改SDK连接至阿里云(二)

    继上篇的阿里云物联云平台设置之后,接下来的工作就是对安信可官方给的sdk进行修改 安信可ESP系列集成环境,SDK,aliyun_mqtt_app,下载地址在上一篇博客,https://www.cnb ...

  9. itextpdf 解析带中文的html问题

    官网连接 官网上有很多DEMO,下面就说几个我碰到的问题! Question: 1. 中文不显示 或者是乱码(本打算用Apache pdfbox来实现业务,但是折腾了一个上午也没解决中午乱码问题,就找 ...

  10. 用命令将本地jar包导入到本地maven仓库

    [**前情提要**]在日常开发过程中,我们总是不可避免的需要依赖某些不在中央仓库,同时也不在本地仓库中的jar包,这是我们就需要使用命令行将需要导入本地仓库中的jar包导入本地仓库,使得项目依赖本地仓 ...