在React ES6中使用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

我知道通常您可以使用export default导入和导出组件,但是我认为如果使用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;

Sites.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 /网站

谢谢你的帮助。

Tarzen Chugh

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

import axios from 'axios';

const helpers = {
    fetchApi: function(){

    }
}

export default helpers;

用法

import helpers from './helpers';

helpers.fetchApi()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章