使用dispatch返回Actions必须是普通对象



我正在使用Redux,并使用连接存储调用异步函数。

这是我的视图文件代码recordings.js,我在其中编写了以下代码:

fetchREcordingJson(file_name) {
const {
dispatch,
history
} = this.props;

dispatch(fetchRecordingJson(file_name))
console.log(dispatch(fetchRecordingJson(file_name)));
}
const mapStateToProps = ({
recordings
}) => {
return {
recordings
};
};
function mapDispatchToProps(dispatch) {
return {
dispatch,
...bindActionCreators({
getRecordingsList,
getRecordingsListById,
getRecordingsListByUserId,
getRecordingsSearchList,
getRecordingsSearchListListByUserId,
getRecordedListWithOrder,
getRecordedListWithOrderbyClient,
getRecordedListWithOrderbyUserId,
getRecordingsTags,
fetchRecordingJson,
}, dispatch)
}
}

export default injectIntl(
connect(mapStateToProps, mapDispatchToProps)(withRouter(RecordingsPage))
);

下面是我的冗余action.js代码:

import axios from 'axios';
import FileDownload from 'react-file-download';
import {
RECEIVE_JSON,
}
from '../actions';
export function receiveJSON(json, file_name) {
return {
type: RECEIVE_JSON,
file_name,
data: json
}
}
export function fetchRecordingJson(file_name) {
return dispatch => {
return axios.get(API_URL + `fetchjson/${file_name}`)
.then(json => {
dispatch(receiveJSON(json.data, file_name))
})
}
}

reducer.js代码:

const INIT_STATE = {
info: {},
data: [],
count: 0,
annotations: [
[]
]
};
case RECEIVE_JSON:
let newState = {
data: action.data.data,
info: action.data.info,
count: state.count
};
newState.annotations = action.data.annotations.length === 0 ? [
[]
] : action.data.annotations || [
[]
];
newState.file_name = action.file_name;
return Object.assign({}, newState);

要么我使用this.props.fetchRecordingJson(file_name)dispatch(fetchRecordingJson(file_name))返回相同的错误

错误:操作必须是纯对象。使用自定义中间件进行异步操作

我花了很多时间来解决这个问题,但没有成功。任何使用redux和dispatch进行异步调用的人都能说出原因以及如何解决这个吗

感谢

就其本身而言,Redux存储对异步逻辑一无所知。您需要使用中间件才能使其工作。这很容易。例如,要添加redux-thunk,您只需要:

// install: npm install redux-thunk
// configure your store
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '<path to your root reducer>';
const store = createStore(rootReducer, applyMiddleware(thunk));

基本上就是这样。

这些文档值得一看:

  • 还原thunk
  • Redux:使用中间件启用异步逻辑
redux上的操作总是必须返回一个对象。如果你想实现异步,你必须使用中间件来定制,比如redux-thunk、redux-saga、observable。。。etc

最新更新