【问题标题】:react redux and thunks / axios / is not a functionreact redux and thunks / axios / is not a function
【发布时间】:2020-03-26 15:37:27
【问题描述】:

您好,我在尝试使用我的 api 时遇到以下错误

TypeError: api.get 不是函数

api.js

从'axios'导入axios;

const api = axios.create({ baseURL: 'http://localhost:8000', });

导出默认api;

动作获取:

const api = require('../../services/api');

export function productsError(bool) {
    return {
        type: 'PRODUCTS_HAS_ERRORED',
        hasErrored: bool
    };
}
export function productsIsLoading(bool) {
    return {
        type: 'PRODUCTS_IS_LOADING',
        isLoading: bool
    };
}
export function productsFetchSuccess(products) {
    return {
        type: 'PRODUCTS_SUCCESS',
        products
    };
}

export function errorAfterFiveSeconds() {
    // We return a function instead of an action object
    return (dispatch) => {
        setTimeout(() => {
            // This function is able to dispatch other action creators
            dispatch(productsError(true));
        }, 5000);
    };
}

export function ProductsFetchData() {
    return (dispatch) => {
        dispatch(productsIsLoading(true));
        api.get('/products')
            .then((response) => {
                if (!response.ok) {
                    throw Error(response.statusText);
                }
                dispatch(productsIsLoading(false));
                return response;
            })
            .then((response) => response.json())
            .then((products) => dispatch(productsFetchSuccess(products)))
            .catch(() => dispatch(productsError(true)));
    };
}

reducer 获取

export function ProductsHasErrored(state = false, action) {
    switch (action.type) {
        case 'PRODUCTS_HAS_ERRORED':
            return action.hasErrored;
        default:
            return state;
    }
}
export function ProductsIsLoading(state = false, action) {
    switch (action.type) {
        case 'PRODUCTS_IS_LOADING':
            return action.isLoading;
        default:
            return state;
    }
}
            return action.products;
        default:
            return state;
    }
}         return action.products;
        default:
            return state;
    }
}export function Products(state = [], action) {
            return action.products;
        default:
            return state;
    }
}         return action.products;
        default:
            return state;
    }
}

我的商店:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

export default function configureStore(initialState) {
    return createStore(
        rootReducer,
        initialState,
        applyMiddleware(thunk)
    );
}

在我的应用中:

import React, { Component } from 'react'
import {connect} from 'react-redux'
import { bindActionCreators } from 'redux';
import { ProductsFetchData } from '../../store/actions/productsFetch';
class index extends Component {

  componentDidMount() {
    this.props.fetchData('/products');
  }


  render() {
    if (this.props.hasErrored) {
          return <p>Sorry! There was an error loading the items</p>;
    }

    if (this.props.isLoading) {
          return <p>Loading…</p>;
    }
    return (
      <div>

      </div>
    )
  }
}

const mapStateToProps = (state) => {
  return {
      products: state.products,
      hasErrored: state.itemsHasErrored,
      isLoading: state.itemsIsLoading
  };
};
const mapDispatchToProps = (dispatch) => {
  return {
      fetchData: () => dispatch(ProductsFetchData())
  };
};
export default connect(mapStateToProps, mapDispatchToProps)(index);

基本上我在这个函数中有错误:

export function ProductsFetchData() {
    return (dispatch) => {
        dispatch(productsIsLoading(true));
        api.get('/products')
            .then((response) => {
                if (!response.ok) {
                    throw Error(response.statusText);
                }
                dispatch(productsIsLoading(false));
                return response;
            })
            .then((response) => response.json())
            .then((products) => dispatch(productsFetchSuccess(products)))
            .catch(() => dispatch(productsError(true)));
    };
}

我不知道为什么或在哪里出错

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    当你使用export default时,这个文件会创建一个key为default的对象并导出。

    const a = 2;
    export default a;
    

    使用要求导入:

    const a = require(...)
    console.log(a)
    // a here will be an object
    >> Object {default: 2}
    

    所以当你想从export default使用require时,你必须访问.defaultconsole.log(a.default)

    或者你可以像这样在 ES6 中使用 import:

    import a from '...';
    // console.log(a)
    >> 2
    

    【讨论】:

      【解决方案2】:

      您应该将 baseURL 导出为 const,然后在您的操作中:

      import axios from 'axios'
      //othercode here 
      export function ProductsFetchData() {
          return (dispatch) => {
              dispatch(productsIsLoading(true));
              api.get(`${}/products`)
                  .then((response) => {
                      if (!response.ok) {
                          throw Error(response.statusText);
                      }
                      dispatch(productsIsLoading(false));
                      return response;
                  })
                  .then((response) => response.json())
                  .then((products) => dispatch(productsFetchSuccess(products)))
                  .catch(() => dispatch(productsError(true)));
          };
      }
      

      【讨论】:

        【解决方案3】:

        在行动抓取中,你应该改变:

        const api = require('../../services/api');
        

        到:

        const api = require('../../services/api').default; 
        

        import api from '../../services/api')
        

        【讨论】:

        • 感谢兄弟,由于某种原因,我变得不确定我测试了我的失眠症,一切正常,你能帮我解决一下吗?
        • 我对其中一个承诺有疑问
        • 我的后端没有问题,它是 100%
        • @Gabriel 你有什么问题?
        • 我的thens有问题,我的结果到了,但是我的result.ok是未定义的,我的.json不起作用
        猜你喜欢
        • 1970-01-01
        • 2021-10-02
        • 2020-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-31
        • 2023-03-06
        • 2019-03-01
        相关资源
        最近更新 更多