我运行redux-loop 官方示例,稍作改动:
- 而不是
fetch
我使用超时的承诺。 - 我添加了日志中间件(来自 redux.js.org 教程的复制粘贴)。
副作用功能:
import {createStore, compose, applyMiddleware} from 'redux';
import {install, loop, Cmd} from 'redux-loop';
function fetchUser(userId) {
return Promise.resolve((res, rej) => setTimeout(() => res(userId), 1000));
}
行动:
function initAction() {
return {
type: 'INIT'
};
}
function userFetchSuccessfulAction(user) {
return {
type: 'USER_FETCH_SUCCESSFUL',
user
};
}
function userFetchFailedAction(err) {
return {
type: 'USER_FETCH_ERROR',
err
};
}
初始状态:
const initialState = {
initStarted: false,
user: null,
error: null
};
减速器:
function reducer(state = initialState, action) {
console.log(action); // I added this line
switch (action.type) {
case 'INIT':
return loop(
{...state, initStarted: true},
Cmd.run(fetchUser, {
successActionCreator: userFetchSuccessfulAction,
failActionCreator: userFetchFailedAction,
args: ['1234']
})
);
case 'USER_FETCH_SUCCESSFUL':
return {...state, user: action.user};
case 'USER_FETCH_FAILED':
return {...state, error: action.error};
default:
return state;
}
}
我的自定义日志中间件:
const logger = store => next => action => {
console.group(action.type);
console.info('dispatching', action);
let result = next(action);
console.log('next state', store.getState());
console.groupEnd();
return result
};
配置商店:
const enhancer = compose(
applyMiddleware(logger),
install()
);
const store = createStore(reducer, initialState, enhancer);
调度第一个动作以开始这一切:(我的代码)
store.dispatch(initAction());
输出: