目前,我正在使用redux感知的 Login
组件发送操作,如下所示,该组件运行良好:
import LoginActions from '../actions';
@connect(store() => store);
...
this.props.dispatch(LoginActions.fetchingUser(formData));
fetchingUser
动作创建者调用一个API,如下所示:
import API from '../utils/api';
...
function fetchingUser(data) {
API.getUser(data)
return {
type: FETCHING_USER
}
api.js
文件的内部如下所示:
getUser: (data) => {
request.post('something.com', data)
.end((err, res) => {
err ? console.log(err) : console.log(res)
})
}
现在,我想要的是能够基于dispatch
LoginActions.js
文件中的API调用响应或直接从 api.js
文件中获取 dispatch()
操作,而要实现这一点,需要在这些位置中的任何一个位置都提供dispatch()
。
app文件夹结构如下(可能不相关):
├── actions
| └── LoginActions.js
├── components
| └── Login.jsx
├── reducer
| └── loginReducer.js
├── utils
└── api.js
发布于 2017-09-20 08:26:17
您可以使用雷克中间件,您可以在您的thunk操作中访问:
function fetchingUser(data) {
return (dispatch, getState) => {
API.getUser(data)
.then(response => {
if(response.condition){
dispatch({type: YOUR_TYPE});
}
})
};
}
不要忘记将中间件添加到商店配置中:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
https://stackoverflow.com/questions/46316819
复制相似问题