reactjs - 在 React ES6 中使用 module.exports

标签 reactjs api ecmascript-6 axios module.exports

我正在尝试使用 module.exports 创建一个“全局”函数,我可以在我的 React 项目中使用它来使用 Axios 进行 API 调用。

我尝试了以下...

import axios from 'axios';

module.exports = {
    fetchApi: function (endPoint) {
        var encodedURI = window.encodeURI('http://localhost:3001/' + endPoint);

        return axios.get(encodeURI)
            .then(function (response) {
                return response.data
            })
    }
}

//call function in other components like this
componentDidMount () {
    fetchApi.fetchApi(this.setState.endPoint)
    .then(function (endPoint) {
        console.log("API endpoint: " + endPoint)
    })
}

这将返回错误...
'fetchApi' 未定义 no-undef

我知道通常您可以使用导出默认值导入和导出组件,但我认为如果使用 module.export,则不需要这样做。

另外,如果我尝试像这样导入...
import fetchApi from '../../../utils/api'

我收到以下错误...
尝试导入错误:“../../../utils/api”不包含默认导出(作为“fetchApi”导入)。

任何帮助表示赞赏。谢谢。

编辑:

从 'axios' 导入 axios;

解决方案(编辑)...

api.js
const api = {
    fetchApi: function(endPoint){
        var encodedURI = window.encodeURI('http://localhost:3001/' + endPoint);
        console.log(encodedURI)

        return axios.get(encodedURI)
            .then(function (response) {
                return response.data

            })
    }
}

export default api;

网站.js
import api from '../../../utils/api'

    //single api call
    componentWillMount = async () => {
        api.fetchApi('sites')
            .then(data => {
                console.log(data);
                this.setState({ rows: data.rows, columns: data.columns })
            })
            .then(async () => {
                this.setState({ tableRows: this.assemblePosts(), isLoading: false })
            });
    }

这使我可以访问以下 api 端点...

http://localhost:3001/sites

谢谢你的帮助。

最佳答案

我建议不要混合使用 require 和 es6 导入语法。坚持使用 es6 语法。
与 es6 语法相同。

import axios from 'axios';

const helpers = {
    fetchApi: function(){

    }
}

export default helpers;

用法
import helpers from './helpers';

helpers.fetchApi()

关于reactjs - 在 React ES6 中使用 module.exports,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57292201/

相关文章:

javascript - 如何保护站点免受 API 中断的影响?

javascript - 表达式插值 Javascript

javascript - 如何在每个函数中使用循环对多个函数进行异步处理

javascript - 为客户端搜索进行多参数过滤的优雅方法

javascript - React/JS 未显示可能性(智能感知)VSCODE

javascript - 使用 ag-grid 进行单元格编辑的自定义日期选择器

javascript - 将 API key 存储在浏览器 cookie 中有什么缺点吗?

api - 使用 Backbone Js 和 SLIM 框架进行用户身份验证

javascript - 我正在阅读关于 promise 的 MDN 文档并想出了一个我无法理解的例子。任何人都可以向我解释流程

reactjs - 还原/ react 。实现后 combineReducers 无法获取应用程序的状态