你的 redux 操作创建者必须是简单的、对象的,并且应该使用强制键来调度和操作type
。但是使用自定义中间件,例如redux-thunk
你可以打电话axios
在您的操作创建者中请求,就像没有自定义一样middlewares
你的动作创建者需要返回普通对象
你的动作创建者看起来像
export function create (values) {
return (dispatch) => {
dispatch({type: CREATE_ORGANIZATION});
axios.post('/url', values)
.then((res) =>{
dispatch({type: CREATE_ORGANIZATION_SUCCESS, payload: res});
})
.catch((error)=> {
dispatch({type: CREATE_ORGANIZATION_FAILURE, payload: error});
})
}
}
你的减速器看起来像
export default (state = initialState, action) => {
const payload = action.payload
switch (action.type) {
case CREATE:
return {
...state,
loading: true,
loaded: false
}
case CREATE_SUCCESS:
return {
...state,
data: state.data.concat(payload.data),
loading: false,
loaded: true,
error: null
}
}
case CREATE_FAILURE:
return {
...state,
loading: false,
loaded: true,
error: payload
}
default:
return state
}
}
现在在创建商店时你可以这样做
import thunk from 'redux-thunk';
import { createStore, applyMiddleware } from 'redux';
const store = createStore(
reducer,
applyMiddleware(thunk)
);
除此之外,您还需要设置 redux 表单
你需要使用combineReducers和Provider来传递store
import reducer from './reducer';
import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form'
export const rootReducer = combineReducers({
reducer,
form: formReducer
})
代码沙盒