React app:保存在gitignored文件中的API密钥返回undefined

问题描述 投票:0回答:1

这真的应该很简单,但我正在开发一个反应式网络应用程序,并在src目录之外的一个名为credentials.js的文件中有一个google API密钥,该文件列在.gitignore中。

作为测试,我在search_bar.js中导入credentials.js,只是为了查看我是否能够传递它来安慰API密钥,但我得到“未定义”作为日志。我尝试了一些我在网上发现但没有运气的建议。我究竟做错了什么?实际的密钥在下面编辑。

//appName/credentials.js
(I've tried adding a semi colon at the end)

export const GOOGLE_API_KEY = 'redacted'


//appName/.gitignore

credentials.js


//appName/components/search_bar.js


import React, { Component } from 'react';
import GOOGLE_API_KEY from '../../credentials.js';

class SearchBar extends Component {

  constructor(props) {
    super(props);
    this.state = { term: '' };
  }

  render() {
      return (
        <div>
          <input
            value={this.state.term}
            onChange={event => {console.log(GOOGLE_API_KEY)}}
          />
        </div>
      );
  }
}

export default SearchBar;
reactjs console gitignore
1个回答
1
投票

您需要对非默认导出使用括号表示法。

尝试:

 import { GOOGLE_API_KEY } from '../../credentials.js';

或使导出默认。

文档:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

© www.soinside.com 2019 - 2024. All rights reserved.