【问题标题】:ACTION didn't attach to reducer despite state of reducer in react-redux尽管 react-redux 中的减速器处于状态,但 ACTION 并未附加到减速器
【发布时间】: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 =&gt; console.log(data.results)))。 console.log 返回 undefined,因此通过将其放在 Promise 链的中间,下一个处理程序会将 undefined 放在操作的有效负载中。删除那条线可以解决问题吗?
  • 您需要为此使用适当的中间件
  • @ZaidCrouch 我也删除了它,但我遇到了同样的错误,
  • 正如我所说,不认为这与您提到的错误有关,但它迟早会绊倒您。 Abinthaha 的问题是正确的:您确定添加了正确的中间件(看起来像 redux-thunk 到您的商店)?

标签: javascript reactjs redux react-redux reducers


【解决方案1】:

你需要让你的动作创建者返回执行异步请求的函数,现在你的动作创建者只返回对象,我们可以使用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
      })
  );
};

【讨论】:

    【解决方案2】:

    感谢回答我问题的人,其实我解决了这个问题很简单。

    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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      • 1970-01-01
      • 2017-10-18
      • 2016-11-24
      • 1970-01-01
      相关资源
      最近更新 更多