redux中的异步解决方案

component中通过dispatch传递action到store中,store通过middleware处理一些功能(异步功能),传递action到reducer,又会返回新的state到store中,store中的state发生改变会触发subscribe来对component重新渲染
redux整个流程本身事同步的
middleware API 来自于redux。redux/applyMiddleware.md at master · reduxjs/redux · GitHub
let store = createStore( reducer ,applyMiddleware(test,logger))
中间件src/store/middleware/logger.js
- // function logger({ getState }) {
- // return next => action => {
- // const returnValue = next(action)
- // return returnValue
- // }
- // }
- export function logger(store){
- return function(next){
- return function(action){
- console.log('1111')
- next(action)
- }
- }
- }
- // 添加异步代码
- export function logger(store){
- return function(next){
- return function(action){
- let t = setTimeout(() => {
- console.log('1111')
- },2000)
- next(action)
- }
- }
- }
中间件 src/store/middleware/test.js
- export function test(store){
- return function(next){
- return function(action){
- console.log('2222')
- next(action)
- }
- }
- }
store/index.js
- import {createStore,applyMiddleware} from 'redux'
- import reducer from './reducer'
- import {logger} from './middleware/logger'
- import {test} from './middleware/test'
- //1. 定义store
- let store = createStore( reducer ,applyMiddleware(test,logger))
- export default store
将异步代码写在 action中,中间件thunk只是告诉我们,谁(action)是异步谁不是
action 返回的是一个函数而不是一个对象
action.js
- // 4. 定义action
- // let increment = {type:'increment'}
- // let decrement = {type:'decrement'}
- // export function increment(){
- // return{
- // type:'increment'
- // }
- // }
- // export function decrement(){
- // return{
- // type:'decrement'
- // }
- // }
- export const increment = (num) => ({ type:'increment',payload:num }) // 同步action
- // export const incrementasync = function(num){
- // return function(dispatch){
- // let t = setTimeout(() => {
- // dispatch(increment(num))
- // },2000)
- // }
- // }
- export const incrementasync = (num) => (dispatch) => { //异步action
- let t = setTimeout(() => {
- dispatch(increment(num))
- },2000)
- }
- export const decrement = (num) => ({ type:'decrement',payload:num })
-
- export const fngreen = () => ({ type:'fngreen'})
- export const fnred = () => ({ type:'fnred' })
中间件thunk.js
- export function thunk(store){
- return function(next){
- return function(action){
- if(typeof action === 'function'){
- action(store.dispatch)
- }else{
- next(action)
- }
- }
- }
- }