我在运行redux-loop official example时做了一点改动:
fetch
。副作用功能:
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());
输出:
答案 0 :(得分:2)
为什么reducer接收的是函数而不是实际的用户对象?
return Promise.resolve((res, rej) => setTimeout(() => res(userId), 1000));
Promise.resolve用于创建已经处于已解决状态的Promise。它希望您传递承诺应解决的价值,在您的情况下,您已要求它解决功能。
您可能打算这样做:
return new Promise((res, rej) => setTimeout(() => res(userId), 1000))