【发布时间】:2018-08-07 07:08:02
【问题描述】:
我为通过 AXIOS 获取 API DATA 设置了操作逻辑,然后作为调度方法,我尝试将接收到的数据置于状态。但此时 action 并没有转到 reducer。
(6) [{…}, {…}, {…}, {…}, {…}, {…}]
index.js:23 Uncaught (in promise) TypeError: dispatch is not a function
at index.js:23
只是我在上面得到了那个错误。这意味着此操作确实获得了 API 数据,然后在尝试分派时失败。我可以找到这个的连接点。
我附上一些 JavaScript:
reducer.js:
import * as types from '../Actions/Types';
const initialState = {
contents: [{
poster: 'https://i.imgur.com/633c18I.jpg',
title: 'state title',
overview: 'state overview',
id: 123,
}],
content: {},
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case types.LOADING_DATA: {
console.log(`something happend ${action.payload}`);
return state.set('contents', action.payload);
}
case types.BTN_ON_CHANGE: {
return state;
}
case types.BTN_ON_CLICK: {
return state;
}
case types.BTN_ON_SUBMIT: {
return state;
}
default:
return state;
}
};
export default reducer;
actions.js
import axios from 'axios';
import * as types from './Types';
const holder = [];
const API_GET = () => (
axios.get('https://api.themoviedb.org/3/search/movie?api_key=<<APIKEY>>&query=avengers+marvel')
.then(res => res.data)
.then(data => console.log(data.results))
.then(results => holder.add(results))
);
// export const loadingData = value => ({
// type: types.LOADING_DATA,
// value,
// });
export const loadingData = () => (dispatch) => {
axios.get('https://api.themoviedb.org/3/search/movie?api_key=54087469444eb8377d671f67b1b8595d&query=avengers+marvel')
.then(res => res.data)
.then(data => console.log(data.results))
.then(results => dispatch({
type: types.LOADING_DATA,
payload: results,
}));
};
export const sample = () => (
console.log('none')
);
LoadingDataButton.js:
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Button } from 'antd';
import { loadingData } from '../Actions';
const LoadingDataButton = props => (
<div>
<Button
type="danger"
onClick={
props.loadingData()
}
>
Loading
</Button>
</div>
);
LoadingDataButton.propTypes = {
loadingData: PropTypes.func.isRequired,
};
const mapStateToProps = state => ({
contents: state.contentR.contents,
});
const mapDispatchToState = {
loadingData,
};
export default connect(mapStateToProps, mapDispatchToState)(LoadingDataButton);
【问题讨论】:
-
你是说你的action没有被reducer拦截?
-
与您提到的错误无关,但在您的
loadingData操作中,您有一个日志记录步骤 (.then(data => console.log(data.results)))。console.log返回 undefined,因此通过将其放在 Promise 链的中间,下一个处理程序会将 undefined 放在操作的有效负载中。删除那条线可以解决问题吗? -
您需要为此使用适当的中间件
-
@ZaidCrouch 我也删除了它,但我遇到了同样的错误,
-
正如我所说,不认为这与您提到的错误有关,但它迟早会绊倒您。 Abinthaha 的问题是正确的:您确定添加了正确的中间件(看起来像
redux-thunk到您的商店)?
标签: javascript reactjs redux react-redux reducers