首页 > 解决方案 > 箭头运算符不返回函数

问题描述

我是这个 es6 大会的新手,已经有几年没有接触 js 了。

什么有效

只有这个有效——

const apiClient = create({
  baseURL: "http://" + IP + ":8990",
  headers: { Authorization: "auth_token" },
});

上面的脚本是在getPosts.js中导入的:

import { apiClient } from "./client";
const endpoint = "/api/";
const getPosts = () => {
  return apiClient.get(endpoint);
};

问题


但是,当我尝试在getPosts.js中导入以下任何内容时,它会说:

TypeError: _client.apiClient.get is not a function.

const apiClient = (auth_token="") => {
  create({
    baseURL: "http://" + IP + ":8990",
    headers: { Authorization: auth_token },
  });
};

const apiClient = () => {
  return create({
    baseURL: "http://" + IP + ":8990",
    headers: { Authorization: "auth_token" },
  });
};

const apiClient = () =>
  create({
    baseURL: "http://" + IP + ":8990",
    headers: { Authorization: "auth_token" },
  });

这是整个文件:

import { create } from "apisauce";
import IP from "../config/network";

const apiClient = create({
  baseURL: "http://" + IP + ":8990",
  headers: { Authorization: "auth_token" },
});

const setAuthToken = (token) => {
  return console.log("in setAuthToken : " + token);
};

export { apiClient, setAuthToken };

我这样做是因为我想将参数传递给函数。谢谢。

标签: javascript

解决方案


在第一种情况下,apiClient设置为函数的返回值,该create函数似乎是具有get属性的对象,在其他情况下,apiClient设置为返回返回值的函数create

你必须使用这样的东西:

apiClient().get(endpoint)

或者

apiClient(token).get(endpoint)

推荐阅读