【发布时间】:2020-03-31 04:13:33
【问题描述】:
我有一个使用 redux-thunk 的 react 项目。我创建了一个将到达端点的操作,然后将存储设置为接收到的数据。目前,我正在使用 .then 但是当我在 componentdidmount 中调用操作时,数据不存在。组件在数据可用之前呈现。为了解决这个问题,我决定将我的操作转换为异步操作,然后在我的 componentdidmount 中等待。问题是,一旦我将 async 放入我的操作中,我就会收到此错误....
Unhandled Rejection (Error): Actions must be plain objects. Use custom middleware for async actions.
这是我的代码
动作
export const getCasesSuccess = async (data) => {
return {
type: GET_ALL_CASES,
data
}
};
export const getAllCases = () => {
return (dispatch) => {
axios.get('https://corona.lmao.ninja/all')
.then(res => {
const cases = res.data
dispatch(getCasesSuccess(cases))
})
.catch(error => {
throw(error)
})
}
}
调用动作的组件
import React from "react";
import { connect } from "react-redux";
import { getAllCases } from "../../store/actions/index";
import AllCases from '../../components/allcases/allCases';
class DataContainer extends React.Component {
constructor(props) {
super(props);
this.state = { }
}
componentDidMount = async () => {
await this.props.getAllCases()
}
render() {
return (
<div>
<AllCases allCases={this.props.allCases} />
</div>
);
}
}
const mapStateToProps = (state) => (
{
allCases: state.allCases
}
)
const mapDispatchToProps = dispatch => {
return {
getAllCases: () => dispatch(getAllCases()),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(DataContainer);
【问题讨论】:
标签: javascript reactjs redux