Ali*_*eed 8 javascript ecmascript-6 redux-saga
我见过传奇以三种方式听取行动:
1. while(true)take()
function* onUserDetailsRequest() {
while(true) {
const { userId } = yield take(USER_DETAILS_REQUESTED);
const response = yield call(fetchUserDetails, userId);
put(USER_DETAILS_RECEIVED, response);
}
}
Run Code Online (Sandbox Code Playgroud)
2. while(take())
function* onUserDetailsRequest() {
while(yield take(USER_DETAILS_REQUESTED)) {
const userId = yield select(userSelectorFn);
const response = yield call(fetchUserDetails, userId);
put(USER_DETAILS_RECEIVED, response);
}
}
Run Code Online (Sandbox Code Playgroud)
3. takeEvery()
function* onUserDetailsRequest() {
yield takeEvery(USER_DETAILS_REQUESTED, function* (action) {
const { userId } = action;
const response = yield call(fetchUserDetails, userId);
put(USER_DETAILS_RECEIVED, response);
}
}
Run Code Online (Sandbox Code Playgroud)
各自的优点和缺点是什么?在哪种情况下我们应该使用另一种情况?
Ben*_*min 10
用代码清除@ AlexM的答案.
cat test.js
const { createStore, applyMiddleware } =require('redux')
const createSagaMiddleware =require('redux-saga').default
const { takeEvery ,take,fork}=require('redux-saga/effects')
const {delay} =require('redux-saga')
const sagaMiddleware = createSagaMiddleware()
const reducer=(state=[],action)=>{return [...state,action.type];}
const store = createStore(
reducer,
applyMiddleware(sagaMiddleware)
)
function* takeSaga() {
while(true){
const action=yield take('testTake')
console.log(action)
yield delay(1000)
}
}
function* takeEverySaga() {
yield takeEvery('testTakeEvery',function* (action){
console.log(action)
yield delay(1000)
})
}
function* takeSagaWithFork() {
while(true){
const action=yield take('testTakeWithFork')
yield fork(function*(){
console.log(action)
yield delay(1000)
})
}
}
sagaMiddleware.run(takeSaga)
sagaMiddleware.run(takeEverySaga)
sagaMiddleware.run(takeSagaWithFork)
const main=async ()=>{
store.dispatch({type: 'testTake'})
store.dispatch({type: 'testTake'})
store.dispatch({type: 'testTakeEvery'})
store.dispatch({type: 'testTakeEvery'})
store.dispatch({type: 'testTakeWithFork'})
store.dispatch({type: 'testTakeWithFork'})
}
main();
Run Code Online (Sandbox Code Playgroud)
用node test.js
will输出运行上面的代码
{ type: 'testTake' }
{ type: 'testTakeEvery' }
{ type: 'testTakeEvery' }
{ type: 'testTakeWithFork' }
{ type: 'testTakeWithFork' }
Run Code Online (Sandbox Code Playgroud)
你看得到差别吗?takeSaga
当第二个testTake
动作被调度时,任务正在休眠,因此takeSaga
完全忽略了第二个testTake
动作.然而,对于takeEverySaga
和takeSagaWithFork
,每当它收到一个testTakeEvery
动作时,一个新的任务被分叉,所以他们在自己的任务"线程"中睡觉,所以不会错过新的动作.因此,takeEvery
基本上与while(true)
+ take
+ 相同fork
.