尽管 react-redux 中的 reducer 状态,但 ACTION 没有附加到 reducer

ACTION didn't attach to reducer despite state of reducer in react-redux

我放置了通过 AXIOS 获取 API DATA 的动作逻辑,然后作为调度方法,我尝试将接收到的数据放入状态。但在这一点上,行动并没有进入减速器。

(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);

您的动作创建者需要 return 函数来执行异步请求,现在您的动作创建者只有 return 个对象,我们可以 return 函数使用 redux-thunk middleware

然后您将编写像这样进行 api 调用的动作创建器

export const fetchThreadData = id => dispatch => {
  dispatch({
    type: FETCH_THREADS_REQUESTING,
    isLoading: true
  });

  const request = axios({
    method: "GET",
    url: "SOME API ADDRESS"
  });

  return request.then(
    response =>
      dispatch({
        type: FETCH_THREADS_SUCCESSFUL,
        payload: response.data,
        isLoading: false
      }),
    error =>
      dispatch({
        type: FETCH_THREADS_FAILED,
        payload: error || "Failed to fetch thread",
        isLoading: false
      })
  );
};

谢谢回答我的问题的各位,其实我用很简单的方法解决了这个问题。

import { createStore, applyMiddleware, compose } from 'redux';
// import saga from 'redux-saga';
import thunk from 'redux-thunk';

import rootReducer from './rootReducer';

const initialState = {};

const middleWare = [thunk];

const store = createStore(
  rootReducer,
  initialState,
  compose(
    applyMiddleware(...middleWare),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
  ),
);

export default store;

我打算做完这个之后使用 SAGA,但是一旦我将中间件更改为 thunk,它就很好用了。也许我需要弄清楚 thunk 是如何工作的。

即使这次我更喜欢使用SAGA,我还是想对Thunk说声谢谢。