首页 > 解决方案 > 我正在使用 axios 在 React 中制作一个 CRUD Web 应用程序。我收到以下错误:“TypeError: Object(...) is not a function”

问题描述

错误: TypeError:Object(...) 不是函数

这是我的代码:

api .js 文件

import axios from "axios";

//url call to the server
const baseUrl = "http://localhost:9000/postmessages";


export default {
  postMessage(url = baseUrl) {
    return {
      fetchAll: () => axios.get(url),
      fetchById: (id) => axios.get(url + id)
    }
  }
}

这是postMessage .js 文件

//import api module
import api from "./api";

//fetchall records with a get request
export const fetchall = () => (dispatch) => {
  api()
  .postMessage()
    .fetchall()
    .then((res) => {
      console.log("postMessage api");
      dispatch({
        type: ACTION_TYPES.FETCH_ALL,
        payload: res.data,
      });
    })
    .catch((err) => console.log(err));
};

我在做什么错或者有什么比我在做什么更好的替代方法

标签: javascriptreactjsapiaxios

解决方案


在你api.js导出一个对象:

export default { //this is an exported object not function
       ...
}

然后您将其称为函数 using (),因此您必须删除它们并像这样使用它:

 api.postMessage()...

详细的 :

//import api module
import api from "./api";

//fetchall records with a get request
export const fetchall = () => (dispatch) => {
  api // omit the ()
  .postMessage()
    .fetchall()
    .then((res) => {
      console.log("postMessage api");
      dispatch({
        type: ACTION_TYPES.FETCH_ALL,
        payload: res.data,
      });
    })
    .catch((err) => console.log(err));
};

推荐阅读