React Middleware
Middleware
Redux-thunk
dispatch
とgetState
をパラメータとして取得する必要があり、thunkはこの関数function createThunkMiddleware(extraArgument){
return ({dispatch,getState})=> (next) => (action) => {
if(typeof action === 'function'){
return action(dispatch, getState, extraArgument)
}
return next(action);
}
}
const thunk = createThunkMiddleware()
thunk.withExtraArgument = createThunkMiddleware;
export default thunk;
Redux-saga
使用方法
$ npm i redux-saga
const sagaMiddleware = createSagaMiddleware();
...
composeWithDevTools(applyMiddleware(sagaMiddleware))
...
sagaMiddleware.run(rootSaga)
sagaモジュール化
// sagas/index.js -- rootsaga
import {all, fork} from 'redux-saga/effects'
import postSaga from './post'
import userSaga from './user'
export default function * rootSaga(){
yield all([
fork(userSaga),
fork(postSaga)
])
}
// sagas/user.js
import {all,fork} from 'redux-saga'
function* logIn(){
try{
//const result = yield call(loginAPI)
yield put({
type:'LOG_IN_SUCCSS',
data:result.data
})
}catch(err){
yield put({
type:'LOG_IN_FAILURE',
data:err.response.data
});
}
}
function loginAPI(){
return axios.post('/api/login')
}
function* logOut(){
try {
const result = yield call(login)
} catch (error) {
}
}
function* watchLogin(){
yield take('LOG_IN_REQUEST',logIn);
}
function* watchLogout(){
yield take('LOG_OUT_REQUEST');
}
export default function* userSaga(){
yield all([
fork(watchLogIn),
fork(watchLogOut)
])
}
saga-effect
import {all, call, fork, put, take} from 'redux-saga/effects'
function loginAPI(){
return axios.post('/api/login')
}
function* logIn(){
try{
const result = yield call(loginAPI)
yield put({
type:'LOG_IN_SUCCSS',
data:result.data
})
}catch(err){
yield put({
type:'LOG_IN_FAILURE',
data:err.response.data
});
}
}
function* watchLogin(){
yield take('LOG_IN',logIn);
}
function* watchLogout(){
yield take('LOG_OUT');
}
function* watchAddPost(){
yield take('ADD_POST')
}
export default function * rootSaga(){
yield all([
call(watchLogin), //fork
call(watchLogout),
call(watchAddPost),
])
}
put
call
fork
呼び出し
take
takeEvery
動作毎に
takeLatest
delay
throttle
debouncing
📑 reference
Reference
この問題について(React Middleware), 我々は、より多くの情報をここで見つけました https://velog.io/@ouo_yoonk/React-Middlewareテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol