【发布时间】:2020-07-11 09:40:33
【问题描述】:
我正在尝试使用 redux 和 react 来调用 api 来获取一些数据。在我的组件中调用该函数时,reducer 没有看到 action.type 并且该函数返回一个已解决的 Promise。我以前没有使用过 redux-thunk。我觉得我的代码应该可以工作,但我很难找到错误。这是代码。
索引.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 |
【问题讨论】:
-
你试过
this.props.getAllCases()吗? -
@AliTorki 当我将其更改为 this.props 时,我收到此错误。
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 | -
提供您的店铺配置代码
-
@AliTorki 它已经在我的 index.js 中提供了
-
createStore 的第二个参数是您未应用的初始状态对象。
const store = createStore(rootReducer, {}, composeWithDevTools(applyMiddleware(thunkMiddleware, devToolsEnhancer)));
标签: javascript reactjs react-redux axios redux-thunk