我正在尝试将redux与react配合使用以进行api调用以获取一些数据。在我的组件中调用该函数时,reducer看不到action.type,并且该函数返回已解决的Promise。我以前没有使用过redux-thunk。我觉得我的代码应该可以工作,但是我很难找到错误。这是代码。
Index.js
const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(thunkMiddleware, devToolsEnhancer)));
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
动作
import axios from 'axios';
export const GET_ALL_CASES = "GET_ALL_CASES";
const getCasesSuccess = (cases) => {
return {
type: GET_ALL_CASES,
cases
}
};
export const getAllCases = () => {
return (dispatch) => {
axios.get('https://corona.lmao.ninja/countries?sort=country')
.then(response => {
dispatch(getCasesSuccess(response.cases))
})
.catch(error => {
throw(error)
})
}
}
减速器
import { GET_ALL_CASES } from '../actions';
const initialState = {
allCases: []
}
const rootReducer = (state = initialState, action) => {
switch (action.type) {
case GET_ALL_CASES:
return { ...state, allCases: [...action.cases]}
default:
return state;
}
}
export default rootReducer;
组件
class Second extends React.Component {
constructor(props) {
super(props);
this.state = { }
}
componentDidMount = () => {
getAllCases()
}
render() {
return (
<div>
{this.props.data[0]}
</div>
);
}
}
const mapStateToProps = (state) => (
{
data: state.allCases
}
)
const mapDispatchToProps = dispatch => {
return {
getAllCases: () => dispatch(getAllCases())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Second);
调用函数时,如果将其更改为this.props.getAllCases(),则会出现此错误。
Unhandled Rejection (Error): Expected the reducer to be a function.
▶ 5 stack frames were collapsed.
getAllCases
C:/Users/Owner/Desktop/corona-app/src/containers/second.js:33
30 |
31 | const mapDispatchToProps = dispatch => {
32 | return {
> 33 | getAllCases: () => dispatch(getAllCases())
| ^ 34 | }
35 | }
36 |
作为对象
const dispatchToProps = {
fun1,
enter,
code,
herefun2
}
作为功能
const mapDispatchToProps = dispatch => {
return {
// dispatching plain actions
increment: () => dispatch({ type: 'INCREMENT' }),
decrement: () => dispatch({ type: 'DECREMENT' }),
reset: () => dispatch({ type: 'RESET' })
}
import React from "react";
import {connect} from "react-redux";
import {getAllCases} from "path-of-the-file";
class Second extends React.Component {
constructor(props) {
super(props);
this.state = {
someState: ""
}
}
componentDidMount () {
const { getAllCases } this.props;
getAllCases()
}
render() {
const {data} = this.props;
return (
<div>
{data[0]}
</div>
);
}
}
const mapStateToProps = (state) => {
return {
data: state.allCases
}
}
const mapDispatchToProps = { getAllCases }
export default connect(mapStateToProps, mapDispatchToProps)(Second);
```