React--Redux工作流程及react-redux

本文参考自https://www.cnblogs.com/goodjobluo/p/9077010.html

Redux工作流程

React--Redux工作流程及react-redux

Redux三大基本原则

  1. 单一事件原则:所有状态和数据都保存在store中,且只存在一个store
  2. 状态只读原则:state数据是只读的,不能直接修改,只能通过派发动作进行处理
  3. 使用纯函数处理:返回值只和传入的参数有关

Action

const add = () => {
   return {
      type : ADD,
      data: 1
   }
}

以上定义了一个名为add的action,type为reducer识别处理的标识,data为传入的数据

reducer

const reducer = (state, action) => {
   switch(action.type){
      case 'ADD':
         state['sum'] = action.data
         return [...state]
         break
      ...
   }
}

以上根据action类型,对state进行处理并返回

store

import {createStore} from 'redux'
let store = createStore(reducer)

以上就创建出了store,store有三个方法:
store.getState() :获取state
store.dispatch(action):派发action
store.subscribe(listener):监听store中数据更新

react-redux

容器组件与傻瓜组件

傻瓜组件仅仅根据父组件传入props渲染数据,容器组件有自己的state,并可以获取store中数据,可以派发action来更改store中的数据

通过connect函数将傻瓜组件转为容器组件,并传入函数参数实现监听store数据更改

connect(mapStateToProps, mapDispatchToProps , mergeProps , options )()
第一个参数为store数据与组件中数据的对应方式,后面几个参数通常省略。返回函数中传入傻瓜组件

class appComponent extends React.component{
      ...
}
mapStateToProps = (state) => {
   return {
      // 本组件中的newItem数据对应state中的newState
      newItem: state.newItem
   }
}
connect(mapStateToProps)(appComponent)

异步中间件

通常情况下,我们需要派发异步action,如发送ajax请求。所以在action发给reducer处理之前,需要通过中间件处理
以下介绍redux-promise-middleWare的使用

//Store.js 加载中间件
import { applyMiddleware,createStore } from 'redux';
import createPromiseMiddleware from 'redux-promise-middleware';
import reducer from './reducers/index';

const store = createStore({//createStore 可以接受应用初始状态作为参数,这时, `applyMiddleware` 就是第三个参数。
	reduer,
	applyMiddleware([createPromiseMiddleware()])
});
export default store;

发起异步action#

//actions.js
export const getTodos = () => {
  const apiUrl = `/todos`;
  return {
    type: GET_TODO,
    //属性 payload 值为 Promise 类型(中间件据此判断是否需要异步处理)
    payload: fetch(apiUrl).then(response => {
      if (!response.ok) {
        //请求返回的可能是500等错误,也会执行到这里,需将状态设置为 rejected
        return Promise.reject(response.status);
      }
      return response.json();
    })
  };
}

处理异步 actions#
一般 action 的处理,发起和处理是一一对应的,而异步 action 则有三个 action 来处理,分别对应异步的三种状态

${GET_TODO}_PENDING 异步请求执行后会立刻 dispatch 此 action,表示请求已发出,正在等待返回值

${GET_TODO}_FULFILLED 异步请求成功后会 dispatch 此 action,注意 Response 只要回来,即使是 500,也会执行到这里

${GET_TODO}_REJECTED 异步请求失败后会 dispatch 此 action

上述三个 action 及后缀皆为中间件redux-promise-middleware的约定,不同中间件约定可能不一致。

//reducer.js
case `${GET_TODO}_PENDING`: {
  return {
    status: FetchStatus.LOADING,
  }
}

case `${GET_TODO}_FULFILLED`: {
  return {status: FetchStatus.SUCCESS, items: action.payload};
}

case `${GET_TODO}_REJECTED`: {
  return {status: FetchStatus.FAILURE, error: action.payload};
}