reactjs React Native :无法从.env文件访问变量

yx2lnoni  于 2022-12-12  发布在  React
关注(0)|答案(2)|浏览(236)

我已经看了很多帖子,读了很多文章,但是没有一篇能帮助我发现这个问题。
1.确保变量从REACT_APP_开始
1.已确保.env文件位于根目录中。
1.确保在编辑.env文件后运行nmp start
我仍然无法访问变量。我正在阅读有关这方面的文章,其中一些文章要求编辑package.json。我尝试了他们所有的命令,但没有一个有效。有人能指导我从这里应该做什么吗?
这里是package.json-

{
  "name": "weatherApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "start:staging": "env-cmd -f .env.staging react-scripts start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "axios": "^1.2.0",
    "dotenv": "^16.0.3",
    "env-cmd": "^10.1.0",
    "react": "18.1.0",
    "react-dotenv": "^0.1.3",
    "react-native": "0.70.6",
    "react-native-dotenv": "^3.4.2"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "babel-jest": "^26.6.3",
    "eslint": "^7.32.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "0.72.3",
    "react-test-renderer": "18.1.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

这是我的目录-

谢谢你!

编辑1:

这就是我访问REACT_APP_API_KEY的方式-

import React, { useState, useEffect } from "react";
import {
  View, 
  Text,
  StyleSheet,
  TextInput, 
  ScrollView
} from 'react-native';

const API_KEY = process.env.REACT_APP_API_KEY

编辑2:

添加-require('dotenv').config()-时出现错误

import React, { useState, useEffect } from "react";
import {
  View, 
  Text,
  StyleSheet,
  TextInput, 
  ScrollView
} from 'react-native';
require('dotenv').config()

const API_KEY = process.env.REACT_APP_API_KEY

编辑3:

这里是我的内容.env文件-

REACT_APP_API_KEY = kfhscahsnfyawciy93874587259784

下面是我在编译代码时遇到的错误-

ERROR  ReferenceError: Property 'REACT_APP_API_KEY' doesn't exist

    This error is located at:
        in WeatherApp
        in RCTView (created by View)
        in View (created by AppContainer)
        in RCTView (created by View)
        in View (created by AppContainer)
        in AppContainer
        in weatherApp(RootComponent), js engine: hermes
1mrurvl1

1mrurvl11#

更新:它工作了!我不得不通过在android/app/build.gradle中添加一个额外的行来设置react-native-config
设置后,.env变量工作正常。

anauzrmj

anauzrmj2#

请执行下列步骤:

  1. npm install dotenv --save
    1.将此行添加到您的应用程序。
    require('dotenv').config()
    1.然后在应用程序的根目录下创建一个.env文件,并向其中添加变量。
// Sample of .env file

REACT_APP_MY_DB_IP = '123.45.78.463'

**注意:**请记住,变量只能以REACT_APP_开头.否则,它将不起作用.每次向.env文件中添加或删除变量时,都需要重新启动应用程序.

相关问题