【发布时间】:2021-01-04 06:47:00
【问题描述】:
我正在使用 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))
);
下面是我的 redux 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 处理异步调用的人都可以说出原因以及如何解决这个问题
谢谢
【问题讨论】:
-
好吧,动作创建者
fetchRecordingJson返回一个函数。那不是一个普通的对象。您是否正确配置了中间件?你用的是什么异步动作库,redux-thunk? -
正如消息中明确指出的那样,如果您想在操作中执行异步操作,则需要使用自定义中间件,例如
redux-thunk -
我没有使用任何库
-
谢谢你们使用 redux-thunk 解决了我的问题。非常感谢您的指导