首页 > 其他分享 >redux-saga

redux-saga

时间:2024-09-08 14:23:49浏览次数:5  
标签:function saga effect next effectTypes export redux

redux-saga

redux-saga

  • redux-saga 是一个 redux 的中间件,而中间件的作用是为 redux 提供额外的功能。
  • 在 reducers 中的所有操作都是同步的并且是纯粹的,即 reducer 都是纯函数,纯函数是指一个函数的返回结果只依赖于它的参数,并且在执行过程中不会对外部产生副作用,即给它传什么,就吐出什么。
    • 所谓纯函数是指没有副作用的函数。副作用就是发生了一些函数外部可观察的变化
      • 输出只依赖输入,不依赖外部变量
      • 不能修改函数作用域之外的变量
  • 但是在实际的应用开发中,我们希望做一些异步的(如Ajax请求)且不纯粹的操作(如改变外部的状态),这些在函数式编程范式中被称为“副作用”。

redux-saga 就是用来处理上述副作用(异步任务)的一个中间件。它是一个接收事件,并可能触发新事件的过程管理者,为你的应用管理复杂的流程。

redux-saga工作原理

  • sages 采用 Generator 函数来 yield Effects(包含指令的文本对象)
  • Generator 函数的作用是可以暂停执行,再次执行的时候从上次暂停的地方继续执行
  • Effect 是一个简单的对象,该对象包含了一些给 middleware 解释执行的信息。
  • 你可以通过使用 effects API 如 fork,call,take,put,cancel 等来创建 Effect。

redux-saga分类

  • worker saga 做具体的工作,如调用API,进行异步请求,获取异步封装结果
  • watcher saga 监听被dispatch的actions,当接受到action或者知道其被触发时,调用worker执行任务
  • root saga 立即启动saga的唯一入口

saga

function* rootSaga() {
    //每次执行next会产出一个effect(指令对象)
    //type用来区分不同的指令 ,比如说PUT是表示想向仓库派发一个action 
    yield { type: 'PUT', action: { type: "ADD" } };
    //还可以产出一个promise
    yield new Promise(resolve => setTimeout(resolve, 3000))
    yield { type: 'PUT', action: { type: "MINUS" } };
}
function runSaga(saga) {
    //执行生成器,得到迭代器
    const it = saga();
    function next() {
        const { done, value: effect } = it.next();
        if (!done) {
            if (effect instanceof Promise) {
                effect.then(next);
            } else if (effect.type === 'PUT') {
                console.log(`向仓库派发一个动作${JSON.stringify(effect.action)}`);
                next();
            } else {
                next();
            }
        }
    }
    next();
}
runSaga(rootSaga);

saga

function * gen(){
    yield 1;
    yield 2;
    yield 3;
}
let it = gen();
console.log(it[Symbol.iterator]);
let r1 = it.next();
console.log(r1);
//let r2 = it.next();
//let r2 = it.throw();
let r2 = it.return();
console.log(r2);
let r3 = it.next();
console.log(r3);
let r4 = it.next();
console.log(r4);

once

只触发一次

let EventEmitter = require('events');
let e = new EventEmitter();
e.once('click',(data)=>{
    console.log('clicked',data);
});
e.emit('click','data');
e.emit('click','data');

计数器

index.js

src/index.js

import React from 'react'
import ReactDOM from 'react-dom';
import Counter from './components/Counter';
import {Provider} from 'react-redux';
import store from './store';
ReactDOM.render(<Provider store={store}>
  <Counter/>
</Provider>,document.querySelector('#root'));

rootSaga.js

src\store\rootSaga.js

import {put,take} from 'redux-saga/effects';
import * as types from './action-types';
function delay(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}
// 工作saga
function * workerSaga(){
  yield delay(1000);
  yield put({type:actionTypes.ADD});
}
function * watcherSaga(){
  //产出一个effect,等待有人向仓库派发一个ASYNC ADD的动作
  //如果等不到,saga就会暂停在这里,如果等到了就会继续向下执行
  //take只监听一次
  yield take(actionTypes.ASYNC_ADD);
  yield workerSaga();
}

export default function* rootSaga() {
  yield watcherSaga();
}

Counter.js

src/components/Counter.js

import React from 'react';
import * as actionTypes from '../store/action-types';
import { useSelector, useDispatch } from 'react-redux';
function Counter() {
    const number = useSelector(state => state.number);
    const dispatch = useDispatch();
    return (
        <div>
            <p>{number}</p>
            <button onClick={() => dispatch({ type: actionTypes.ASYNC_ADD })}>+</button>
        </div>
    )
}
export default Counter;

index.js

src/store/index.js

import {createStore, applyMiddleware} from 'redux';
import reducer from './reducer';
import createSagaMiddleware from 'redux-saga';
import rootSaga from './sagas';
let sagaMiddleware=createSagaMiddleware();
let store=applyMiddleware(sagaMiddleware)(createStore)(reducer);
sagaMiddleware.run(rootSaga);
window.store=store;
export default store;

action-types.js

src/store/action-types.js

export const ASYNC_ADD='ASYNC_ADD';
export const ADD='ADD';

reducer.js

src/store/reducer.js

import * as types from './action-types';
export default function reducer(state={number:0},action) {
    switch(action.type){
        case types.ADD:
            return {number: state.number+1};
        default:
            return state;
    }
}

实现take

effectTypes.js

src\redux-saga\effectTypes.js

export const TAKE = 'TAKE';
export const PUT = 'PUT';

effects.js

src\redux-saga\effects.js

import * as effectTypes from './effectTypes'
export function take(actionType) {
    return { type: effectTypes.TAKE, actionType}
}

export function put(action) {
    return { type: effectTypes.PUT, action }
}

runSaga.js

src\redux-saga\runSaga.js

import * as effectTypes from './effectTypes'
export default function runSaga(env, saga) {
    let { channel, dispatch } = env;
    let it = typeof saga === 'function'?saga():saga;
    function next(value) {
        let {value:effect,done} = it.next(value);
        if (!done) {
            if(typeof effect[Symbol.iterator] === 'function'){
                runSaga(env,effect);
                next();//不会阻止当前saga继续向后走
            }else if (effect instanceof Promise) {
                effect.then(next);
            }else{
                switch (effect.type) {
                    case effectTypes.TAKE:
                        channel.once(effect.actionType,next);
                        break;
                    case effectTypes.PUT:
                        dispatch(effect.action);
                        next();
                        break;
                    default:
                        break;
               }
            }

        }
    }
    next();
}

index.js

redux-saga/index.js

import EventEmitter from 'events';
import runSaga from './runSaga';
export default function createSagaMiddleware() {
    let channel = new EventEmitter();
    let boundRunSaga;
    function sagaMiddleware({getState,dispatch}) {
        boundRunSaga=runSaga.bind(null,{channel,dispatch,getState});
        return function (next) {
            return function (action) {
                const result = next(action);
                channel.emit(action.type, action);
                return result;
            }
        }
    }
    sagaMiddleware.run = (saga)=>boundRunSaga(saga);
    return sagaMiddleware;
}

支持fork

开启一个新的"子进程",也就是从头开始

sagas.js

+import { put, takeEvery } from '../redux-saga/effects';
import * as actionTypes from './action-types';
+const delay = (ms)=>{
+    return new Promise(resolve=>{
+        setTimeout(resolve,ms);
+    });
+}
+export function* workerSaga() {
+    yield delay(1000);
+    yield put({ type: actionTypes.ADD });
+}
+function * watcherSaga(){
+    const action = yield take(actionTypes.ASYNC_ADD);
+    yield fork(workerSaga);
+}
+export default function* rootSaga() {
+   yield watcherSaga();
+}

effectTypes.js

src\redux-saga\effectTypes.js

export const TAKE = 'TAKE';
export const PUT = 'PUT';
+export const FORK = 'FORK';

effects.js

src\redux-saga\effects.js

import * as effectTypes from './effectTypes'
export function take(actionType) {
    return { type: effectTypes.TAKE, actionType }
}

export function put(action) {
    return { type: effectTypes.PUT, action }
}

+export function fork(saga) {
+    return { type: effectTypes.FORK, saga };
+}

runSaga.js

src\redux-saga\runSaga.js

import * as effectTypes from './effectTypes'
export default function runSaga(env, saga) {
    let { channel, dispatch } = env;
    let it = typeof saga == 'function' ? saga() : saga;
    function next(value) {
        let { value: effect, done } = it.next(value);
        if (!done) {
            if (typeof effect[Symbol.iterator] == 'function') {
                runSaga(env,effect);
                next();
            } else {
                switch (effect.type) {
                    case effectTypes.TAKE:
                        channel.take(effect.actionType, next);
                        break;
                    case effectTypes.PUT:
                        dispatch(effect.action);
                        next();
                        break;
+                    case effectTypes.FORK:
+                        runSaga(env,effect.saga);
+                        next();
+                        break;
                    default:
                        break;
                }
            }

        }
    }
    next();
}

支持takeEvery

  • 一个 task 就像是一个在后台运行的进程,在基于redux-saga的应用程序中,可以同时运行多个task
  • 通过 fork 函数来创建 task

sagas.js

+import { put, takeEvery } from '../redux-saga/effects';
import * as actionTypes from './action-types';
export function* add() {
    yield put({ type: actionTypes.ADD });
}
export default function* rootSaga() {
+    yield takeEvery(actionTypes.ASYNC_ADD,add);
}

effects.js

src\redux-saga\effects.js

import * as effectTypes from './effectTypes'
export function take(actionType) {
    return { type: effectTypes.TAKE, actionType }
}

export function put(action) {
    return { type: effectTypes.PUT, action }
}

export function fork(saga) {
    return { type: effectTypes.FORK, saga };
}

+export function takeEvery(actionType, saga) {
+    function* takeEveryHelper() {
+        while (true) {
+            yield take(actionType);
+            yield fork(saga);
+        }
+    }
+    return fork(takeEveryHelper);
+}

支持 call

让saga中间件调用一个函数,函数会返回一个promise,等promise完成后继续向下执行

sagas.js

src\store\sagas.js

+import { put, takeEvery,call } from '../redux-saga/effects';
import * as actionTypes from './action-types';
const delay = ms => new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve();
    }, ms);
});
export function* add() {
+    yield call(delay,1000);
    yield put({ type: actionTypes.ADD });
}
export default function* rootSaga() {
    yield takeEvery(actionTypes.ASYNC_ADD, add);
}

effectTypes.js

src\redux-saga\effectTypes.js

export const TAKE = 'TAKE';
export const PUT = 'PUT';
export const FORK = 'FORK';
+export const CALL = 'CALL';

effects.js

src\redux-saga\effects.js

import * as effectTypes from './effectTypes'
export function take(actionType) {
    return { type: effectTypes.TAKE, actionType }
}

export function put(action) {
    return { type: effectTypes.PUT, action }
}

export function fork(saga) {
    return { type: effectTypes.FORK, saga };
}

export function takeEvery(pattern, saga) {
    function* takeEveryHelper() {
        while (true) {
            yield take(pattern);
            yield fork(saga);
        }
    }
    return fork(takeEveryHelper);
}
+export function call(fn, ...args) {
+    return { type: effectTypes.CALL, fn, args };
+}

runSaga.js

src\redux-saga\runSaga.js

import * as effectTypes from './effectTypes'
export default function runSaga(env, saga) {
    let { channel, dispatch } = env;
    let it = typeof saga == 'function' ? saga() : saga;
    function next(value) {
        let { value: effect, done } = it.next(value);
        if (!done) {
            if (typeof effect[Symbol.iterator] == 'function') {
                runSaga(env,effect);
                next();
            }else if(effect.then){
                effect.then(next);
            } else {
                switch (effect.type) {
                    case effectTypes.TAKE:
                        channel.take(effect.actionType, next);
                        break;
                    case effectTypes.PUT:
                        dispatch(effect.action);
                        next();
                        break;
                    case effectTypes.FORK:
                        runSaga(env,effect.saga);
                        next();
                        break;
+                    case effectTypes.CALL:
+                        effect.fn(...effect.args).then(next);
+                        break;
                    default:
                        break;
                }
            }

        }
    }
    next();
}

支持 cps

saga中间件调用一个函数,此函数在执行结束后会调用最后一个参数,就是callback,继续向下执行本saga

sagas.js

src\store\sagas.js

+import { put, takeEvery,call,cps} from '../redux-saga/effects';
import * as actionTypes from './action-types';
+const delay = (ms,callback)=>{
+    setTimeout(() => {
+        callback(null,'ok');
+    },ms);
+}
export function* add() {
+    let data = yield cps(delay,1000);
+    console.log(data);
    yield put({ type: actionTypes.ADD });
}
export default function* rootSaga() {
    yield takeEvery(actionTypes.ASYNC_ADD, add);
}

effectTypes.js

src\redux-saga\effectTypes.js

export const TAKE = 'TAKE';
export const PUT = 'PUT';
export const FORK = 'FORK';
export const CALL = 'CALL';
+export const CPS = 'CPS';

effects.js

src\redux-saga\effects.js

import * as effectTypes from './effectTypes'
export function take(actionType) {
    return { type: effectTypes.TAKE, actionType }
}

export function put(action) {
    return { type: effectTypes.PUT, action }
}

export function fork(saga) {
    return { type: effectTypes.FORK, saga };
}

export function takeEvery(pattern, saga) {
    function* takeEveryHelper() {
        while (true) {
            yield take(pattern);
            yield fork(saga);
        }
    }
    return fork(takeEveryHelper);
}
export function call(fn, ...args) {
    return { type: effectTypes.CALL, fn, args };
}
+export function cps(fn, ...args) {
+    return { type: effectTypes.CPS, fn, args };
+}

runSaga.js

src\redux-saga\runSaga.js

import * as effectTypes from './effectTypes'
export default function runSaga(env, saga) {
    let { channel, dispatch } = env;
    let it = typeof saga == 'function' ? saga() : saga;
+    function next(value,isErr) {
+        let result;
+        if (isErr) {
+            result = it.throw(value);
+          } else {
+            result = it.next(value);
+          }
+        let { value: effect, done } = result;
        if (!done) {
            if (typeof effect[Symbol.iterator] == 'function') {
                runSaga(env,effect);
                next();
            }else if(effect.then){
                effect.then(next);
            } else {
                switch (effect.type) {
                    case effectTypes.TAKE:
                        channel.take(effect.actionType, next);
                        break;
                    case effectTypes.PUT:
                        dispatch(effect.action);
                        next();
                        break;
                    case effectTypes.FORK:
                        runSaga(env,effect.saga);
                        next();
                        break;
                    case effectTypes.CALL:
                        effect.fn(...effect.args).then(next);
                        break;
+                    case effectTypes.CPS:
+                        effect.fn(...effect.args,(err,data)=>{
+                            if(err){
+                                next(err,true);
+                            }else{
+                                next(data);
+                            }
+                        });
+                        break;    
                    default:
                        break;
                }
            }

        }
    }
    next();
}

支持all

提供多个saga,需要等多个saga全部完成了才会继续向下执行当前的saga

saga

src\store\sagas.js

import { put, takeEvery, call, cps, take,all } from '../redux-saga/effects';
import * as actionTypes from './action-types';
+export function* add1() {
+    for (let i = 0; i < 1; i++) {
+        yield take(actionTypes.ASYNC_ADD);
+        yield put({ type: actionTypes.ADD });
+    }
+    console.log('add1 done ');
+    return 'add1Result';
+}
+export function* add2() {
+    for (let i = 0; i < 2; i++) {
+        yield take(actionTypes.ASYNC_ADD);
+        yield put({ type: actionTypes.ADD });
+    }
+    console.log('add2 done ');
+    return 'add2Result';
+}
export default function* rootSaga() {
+    let result = yield all([add1(), add2()]);
+    console.log('done', result);
}

effectTypes.js

src\redux-saga\effectTypes.js

export const TAKE = 'TAKE';
export const PUT = 'PUT';
export const FORK = 'FORK';
export const CALL = 'CALL';
export const CPS = 'CPS';
export const ALL = 'ALL';

effects.js

src\redux-saga\effects.js

import * as effectTypes from './effectTypes'
export function take(actionType) {
    return { type: effectTypes.TAKE, actionType }
}

export function put(action) {
    return { type: effectTypes.PUT, action }
}

export function fork(saga) {
    return { type: effectTypes.FORK, saga };
}

export function takeEvery(pattern, saga) {
    function* takeEveryHelper() {
        while (true) {
            yield take(pattern);
            yield fork(saga);
        }
    }
    return fork(takeEveryHelper);
}
export function call(fn, ...args) {
    return { type: effectTypes.CALL, fn, args };
}
export function cps(fn, ...args) {
    return { type: effectTypes.CPS, fn, args };
}
+export function all(iterators) {
+    return { type: effectTypes.ALL, iterators };
+}

runSaga.js

src\redux-saga\runSaga.js

import * as effectTypes from './effectTypes'
+export default function runSaga(env, saga,callback) {
    let { channel, dispatch } = env;
    let it = typeof saga == 'function' ? saga() : saga;
    function next(value, isErr) {
        let result;
        if (isErr) {
            result = it.throw(value);
        } else {
            result = it.next(value);
        }
        let { value: effect, done } = result;
        if (!done) {
            if (typeof effect[Symbol.iterator] == 'function') {
                runSaga(env, effect);
                next();
            } else if (effect.then) {
                effect.then(next);
            } else {
                switch (effect.type) {
                    case effectTypes.TAKE:
                        channel.take(effect.actionType, next);
                        break;
                    case effectTypes.PUT:
                        dispatch(effect.action);
                        next();
                        break;
                    case effectTypes.FORK:
                        runSaga(env, effect.saga);
                        next();
                        break;
                    case effectTypes.CALL:
                        effect.fn(...effect.args).then(next);
                        break;
                    case effectTypes.CPS:
                        effect.fn(...effect.args, (err, data) => {
                            if (err) {
                                next(err, true);
                            } else {
                                next(data);
                            }
                        });
                        break;
+                    case effectTypes.ALL:
+                        const { iterators } = effect;
+                        let result = [];
+                        let count = 0;
+                        iterators.forEach((iterator, index) => {
+                        runSaga(env, iterator, (data) => {
+                            result[index] = data;
+                            if (++count === iterators.length) {
+                            next(result);
+                            }
+                        });
+                        });
+                        break;
                    default:
                        break;
                }
            }
        } else {
+            callback && callback(effect);
        }
    }
    next();
}

取消任务

sagas.js

src\store\sagas.js

+import { put, takeEvery, call, cps, all, take, cancel, fork, delay } from '../redux-saga/effects';
+import * as actionTypes from './action-types';
+export function* add() {
+    while (true) {
+        yield delay(1000);
+        yield put({ type: actionTypes.ADD });
+    }
+}
+export function* addWatcher() {
+    const task = yield fork(add);
+    console.log(task);
+    yield take(actionTypes.STOP_ADD);
+    yield cancel(task);
+}
+function* request(action) {
+    let url = action.payload;
+    let promise = fetch(url).then(res => res.json());;
+    let res = yield promise;
+    console.log(res);
+}
+
+function* requestWatcher() {
+    //action = {type,url}
+    const requestAction = yield take(actionTypes.REQUEST);
+    //开启一个新的子进程发起请求
+    const requestTask = yield fork(request, requestAction);
+    //立刻开始等待停止请求的动作类型
+    const stopAction = yield take(actionTypes.STOP_REQUEST);
+    yield cancel(requestTask);//在axios里,是通过 调用promise的reject方法来实出任务取消
+}
+export default function* rootSaga() {
+    yield addWatcher();
+    yield requestWatcher();
+}

effectTypes.js

src\redux-saga\effectTypes.js

export const TAKE = 'TAKE';
export const PUT = 'PUT';
export const FORK = 'FORK';
export const CALL = 'CALL';
export const CPS = 'CPS';
export const ALL = 'ALL';
+export const CANCEL = 'CANCEL';

effects.js

src\redux-saga\effects.js

import * as effectTypes from './effectTypes'
export function take(actionType) {
    return { type: effectTypes.TAKE, actionType }
}

export function put(action) {
    return { type: effectTypes.PUT, action }
}

export function fork(saga) {
    return { type: effectTypes.FORK, saga };
}

export function takeEvery(pattern, saga) {
    function* takeEveryHelper() {
        while (true) {
            yield take(pattern);
            yield fork(saga);
        }
    }
    return fork(takeEveryHelper);
}
export function call(fn, ...args) {
    return { type: effectTypes.CALL, fn, args };
}
export function cps(fn, ...args) {
    return { type: effectTypes.CPS, fn, args };
}
export function all(effects) {
    return { type: effectTypes.ALL, effects };
}
+const delayFn = (ms) => {
+    return new Promise(resolve => {
+        setTimeout(resolve, ms);
+    })
+}
+export function delay(...args) {
+    return call(delayFn, ...args);
+}
+export function cancel(task) {
+    return { type: effectTypes.CANCEL, task };
+}

runSaga.js

src\redux-saga\runSaga.js

import * as effectTypes from './effectTypes';
const CANCEL_TASK = 'CANCEL_TASK';
export default function runSaga(env, saga,callback) {
+    let task = {cancel:()=>next(TASK_CANCEL)};
    let { channel, dispatch } = env;
    let it = typeof saga == 'function' ? saga() : saga;
    function next(value, isErr) {
        let result;
        if (isErr) {
            result = it.throw(value);
+        }else if(value === TASK_CANCEL){
+            result = it.return(value);
        } else {
            result = it.next(value);
        }
        let { value: effect, done } = result;
        if (!done) {
            if (typeof effect[Symbol.iterator] == 'function') {
                runSaga(env, effect);
                next();
            } else if (effect.then) {
                effect.then(next);
            } else {
                switch (effect.type) {
                    case effectTypes.TAKE:
                        channel.take(effect.actionType, next);
                        break;
                    case effectTypes.PUT:
                        dispatch(effect.action);
                        next();
                        break;
                    case effectTypes.FORK:
+                        let forkTask = runSaga(env, effect.saga);
+                        next(forkTask);
                        break;
                    case effectTypes.CALL:
                        effect.fn(...effect.args).then(next);
                        break;
                    case effectTypes.CPS:
                        effect.fn(...effect.args, (err, data) => {
                            if (err) {
                                next(err, true);
                            } else {
                                next(data);
                            }
                        });
                        break;
                    case effectTypes.ALL:
                        const { iterators } = effect;
                        let result = [];
                        let count = 0;
                        iterators.forEach((iterator, index) => {
                            runSaga(env, iterator, (data) => {
                                result[index] = data;
                                if (++count === iterators.length) {
                                next(result);
                                }
                            });
                        });
                        break;
+                    case effectTypes.CANCEL:
+                        effect.task.cancel();
+                        next();
+                        break;    
                    default:
                        break;
                }
            }
        } else {
            callback && callback(effect);
        }
    }
    next();
+    return task;
}

action-types.js

src\store\action-types.js

export const ASYNC_ADD='ASYNC_ADD';
export const ADD='ADD';
+export const STOP='STOP';

+export const REQUEST = 'REQUEST';
+export const STOP_REQUEST = 'STOP_REQUEST';

Counter.js

src\components\Counter.js

import React from 'react';
import * as actionTypes from '../store/action-types';
import { useSelector, useDispatch } from 'react-redux';
function Counter() {
    const number = useSelector(state => state.number);
    const dispatch = useDispatch();
    return (
        <div>
            <p>{number}</p>
+            <button onClick={() => dispatch({ type: actionTypes.ASYNC_ADD })}>+</button>
+            <button onClick={() => dispatch({ type: actionTypes.STOP_ADD })}>stop</button>
+            <button onClick={() => dispatch({ type: actionTypes.REQUEST, payload: '/users.json' })}>request</button>
+            <button onClick={() => dispatch({ type: actionTypes.STOP_REQUEST })}>stopRequest</button>
        </div>
    )
}
export default Counter;

标签:function,saga,effect,next,effectTypes,export,redux
From: https://blog.csdn.net/qq_40588441/article/details/142026454

相关文章

  • redux-first-history
    redux-first-history这是一个把redux仓库和路由连接的库它有两个作用把地址栏中的新的路径保存到redux仓库中可以通过派发动作的方式跳转路径生成项目redux-first-historyReduxhistorybindingforreact-routercreate-react-apphs_redux_first_historycdhs_r......
  • Redux 中间件的实现原理
    Redux中间件的实现原理主要基于函数式编程思想和高阶函数。中间件用于在Redux的dispatch过程之间插入自定义逻辑,如日志记录、异步操作、调试工具等。1.什么是Redux中间件?简要介绍Redux中间件的概念和用途。解释中间件如何在dispatch动作和到达reducer之间插入逻......
  • react-navigation使用redux-saga等处理各种跳转、清除堆栈、返回不同页面的问题
    react-navigation使用redux-saga等处理各种跳转、清除堆栈、返回不同页面的问题名字还是土一点好关注IP属地:上海0.272018.01.2114:26:36字数154阅读4,027一直没有找到有关于 react-navigation 处理app各种不同状态需要默认不同首页的例子,于是只能自己写了。整个......
  • AT、TCC、SAGA 和 XA 事务模式
    分布式事务是指跨多个服务或数据库的事务,这些事务需要在各个参与者之间保持一致性。以下是四种常见的分布式事务模式:AT(AutomaticTransaction)、TCC(Try-Confirm/Cancel)、SAGA和XA事务模式。1.AT(AutomaticTransaction)简介:AT是由阿里巴巴提出的分布式事务解决方案,属于......
  • Redux 及Redux-Toolkit 使用笔记及简易实现
    Redux及Redux-Toolkit使用笔记及简易实现依赖的包npminstall@reduxjs/toolkitreact-redux创建Store并且将它注入到app中。一般使用configureStore({reducers:{}}),这种方式,我们可以在各个模块里面定义各自的reducer,然后在store里面使用它。这个方法返回的就是store的实......
  • 快速上手Redux (redux的基本使用)
    什么是Redux?        Redux是一个用于管理JavaScript应用程序状态的库,专注于解决应用程序中状态管理的问题。简单来说就是可以使各组件实现对数据共享和操作,类似于Vue中的Pinia和Vuex。Redux虽然是一个框架无关可以独立运行的插件,但是社区通常还是把它与React绑定在一......
  • [email protected](62)[email protected](11)- 中间件2 - redux-thunk
    目录1,介绍举例2,原理和实现实现3,注意点1,介绍一般情况下,action是一个平面对象,并会通过纯函数来创建。exportconstcreateAddUserAction=(user)=>({type:ADD_USER,payload:user,});这样是有一些限制的无法使用异步的,比如在请求接口之后再做一......
  • [email protected](53)[email protected](2)- action
    目录1,特点1.1,payload1.2,type1.3,bindActionCreators1,特点是一个平面对象(plain-object)。换句话说,就是通过字面量创建的对象,它的__proto__指向Object.prototype。该对象有2个属性:constaction={ type:'add', payload:3}1.1,payload表示额外需要传递的附......
  • [email protected](52)[email protected](1)- 核心概念
    目录1,MVC2,前端MVC的困难3,Flux4,Redux1,MVC是一个解决方案,用于降低UI和数据关联的复杂度。在早期前后端未做分离时,服务端会响应一个完整的HTML,包含页面需要的所有数据。而浏览器仅承担渲染页面的作用,整体流程也就是服务端渲染。其中服务端的处理流程:处理请求,并将......
  • 【react】react-redux 使用指南
    React-Redux使用指南如下:一、引言React-Redux是为React框架设计的一个状态管理库,它基于Redux,但提供了更加便捷的方式来与React组件进行交互。通过React-Redux,你可以在整个应用程序中维护一个单一的数据源(即ReduxStore),并通过action和reducer来管理这个数据源......