快速上手redux,react-redux中间件

redux基本用法

redux数据更新流程图


QQ截图20190910103759.png

Store管理数据显示UI界面,界面交互触发dispatch(action)根据action触发Reducers根据数据

//store.js
import {createStore} from 'redux'
const counterReducer = (state = 0, action) => {//Reducers
  switch (action.type) {
   case 'add':
    return state + 1
   case 'minus':
    return state - 1
   default:
    return state
 }
}
const store = createStore(counterReducer) //创建store数据管理仓库
export default store
//Test.js
import React, { Component } from "react";
import store from "../store";//引入之前创建的
export default class ReduxTest extends Component {
 componentDidMount(){
    store.subscribe(()=>{
      this.forceUpdate()
    })//监听每次数据更新时调用的方法
  }
 render() {
  return (
  

{store.getState()}

//获取store.js counterReducer 初始化的 state
//触发事件根绝type更改state
); } }

vuex是专门为vue开发,依赖vue进行了数据的变更劫持
redux要配合react-redux,每次数据更改的时候可以render

//npm install react-redux --save  
//index.js
import React from 'react'
import ReactDom from 'react-dom'
import App from './App'
import store from './store'
import { Provider } from 'react-redux'//相当于理解成为React.createContext().
ReactDom.render(
 
  
 ,
 document.querySelector('#root')
)

Test.js修改为

import React, { Component } from "react";
import { connect } from "react-redux";
@connect(
 state => ({ num: state }), // 状态映射
{
  add: () => ({ type: "add" }), // action creator
  minus: () => ({ type: "minus" }) // action creator
}
)
export default class ReduxTest extends Component {

 render() {
  return (
  

{this.props.num}

state
); } }
中间件

npm install redux-thunk redux-logger --save
redux-logger 每次更改redux 可以consoe.log相关信息
redux-thunk 返回一个函数来解决异步
官网规定Reducer为纯函数 所以dispatch要执行异步要增加中间件

import { createStore, applyMiddleware } from "redux";
import logger from "redux-logger";
import thunk from "redux-thunk";
const store = createStore(fruitReducer, applyMiddleware(logger, thunk));

redux代码优化、模块化

新建store文件夹管理
每个reducer和对应的方法放在同一文件下

//store/counter.js
export const counterReducer = (state = 0, action) => {
switch (action.type) {
   case 'add':
    return state + 1
   case 'minus':
    return state - 1
   default:
    return state
 }
};
export const add = num => ({ type: "add", payload: num });
export const minus = num => ({ type: "minus", payload: num });

store/index.js 来整合store文件下的各reducer

import {combineReducers} "redux"
import {counterReducer} from './counter' 
const Reducers= combineReducers({counter:counterReducer})
const store = createStore(Reducers, applyMiddleware(logger, thunk));
export default store;

Test.js调用优化后、模块化后的reducer

import React, { Component } from "react";
import { connect } from "react-redux";
import {add,minus} from "./store/counter"//引入修改reducer方法
@connect(
 state => ({ num: state.counter}), // 模块化状态映射
{
  add,
  minus
}
)
export default class ReduxTest extends Component {
 render() {
  return (
  

{this.props.num}

); } }

你可能感兴趣的:(快速上手redux,react-redux中间件)