如何存储配置文件并使用React读取它 [英] How to store Configuration file and read it using React

查看:3292
本文介绍了如何存储配置文件并使用React读取它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <$ c。我已经实现了一个组件,其中我从服务器获取数据并使用它像

$ c> CallEnterprise:function(TenantId){


fetchData('http://xxx.xxx.xx.xx:8090 / Enterprises?TenantId ='+ TenantId +'& format = json')。then(function(enterprises)
{
EnterprisePerspectiveActions.getEnterprise(enterprises);
})catch(function()
{
alert API呼叫有一些问题,请联系管理员);
//ComponentAppDispatcher.handleViewAction({
// actionType:MetaItemConstants.RECEIVE_ERROR,
//错误:'有一个问题获得企业的
//});
});
},

我想在配置文件中存储Url,服务器或在生产我不得不只是更改配置文件的URL不在js文件,但我不知道如何使用配置文件在react.js



任何人请指导我如何实现这个?

解决方案

使用webpack你可以将env特定的配置放入

 <$ c>的 $ c> externals:{
'Config':JSON.stringify(process.env.ENV ==='production'?{
serverUrl:https://myserver.com
}:{
serverUrl:http:// localhost:8090
})
}

$ b b

如果你想将配置存储在一个单独的JSON文件中,那么你可以要求该文件并分配到 Config



  externals:{
'Config':JSON.stringify(production?require('./ config.prod.json' ):require('./ config.dev.json'))
}

在你的模块中,你可以使用config:

  var Config = require('Config')
fetchData http://'+ Config.serverUrl +'/ Enterprises / ...')

如果它涵盖了你的用例,但它已经为我们工作得很好。


I am new on react.js I have implemented one component in which I am fetching the data from server and use it like,

CallEnterprise:function(TenantId){


    fetchData('http://xxx.xxx.xx.xx:8090/Enterprises?TenantId='+TenantId+' &format=json').then(function(enterprises) 
    {
        EnterprisePerspectiveActions.getEnterprise(enterprises);
    }).catch(function()
    {
        alert("There was some issue in API Call please contact Admin");
        //ComponentAppDispatcher.handleViewAction({
        //    actionType: MetaItemConstants.RECEIVE_ERROR,
        //    error: 'There was a problem getting the enterprises'
        //});
    });
},

I want to store Url in configuration file so when I deployed this on Testing server or on Production I have to just change the url on config file not in js file but I don't know how to use configuration file in react.js

Can anyone please guide me how can I achieve this ?

解决方案

With webpack you can put env-specific config into the externals field in webpack.config.js

externals: {
  'Config': JSON.stringify(process.env.ENV === 'production' ? {
    serverUrl: "https://myserver.com"
  } : {
    serverUrl: "http://localhost:8090"
  })
}

If you want to store the configs in a separate JSON file, that's possible too, you can require that file and assign to Config:

externals: {
  'Config': JSON.stringify(production ? require('./config.prod.json') : require('./config.dev.json'))
}

Then in your modules, you can use the config:

var Config = require('Config')
fetchData('http://' + Config.serverUrl + '/Enterprises/...')

Not sure if it covers your use case but it's been working pretty well for us.

这篇关于如何存储配置文件并使用React读取它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆