Javascript 在异步作用域中嵌入ReactDOM.render
我目前正在维护一个在react版本15.4.2下开发的基于类的组件项目。 所有项目组件都使用名为DBLINK的硬编码变量来访问web API。该变量是从辅助文件导出的Javascript 在异步作用域中嵌入ReactDOM.render,javascript,reactjs,Javascript,Reactjs,我目前正在维护一个在react版本15.4.2下开发的基于类的组件项目。 所有项目组件都使用名为DBLINK的硬编码变量来访问web API。该变量是从辅助文件导出的 //exported from helper.js export const DB_LINK = window.location.protocol +"//" + window.location.hostname + "/webservice.svc/web/" //imported f
//exported from helper.js
export const DB_LINK = window.location.protocol +"//" + window.location.hostname + "/webservice.svc/web/"
//imported from helper.js to use in API calls
import { DB_LINK } from '../helper';
新的业务规范要求从本地文件(conn.json)(或其他后台API)读取变量,而不是硬编码为常量
因此,我不得不修改helper.js以相应地读取值
let DB_LINK = null
export const set_DB_LINK = async () => {
if (!DB_LINK) {
let path = `${process.env.PUBLIC_URL}/conn.json`
console.log(path)
//console.log('reading ',`${process.env.PUBLIC_URL}/conn.json`)
let response = await axios.get(`${process.env.PUBLIC_URL}/conn.json`).catch(err=>console.log(err))
DB_LINK = eval(response.data.urlPath)
console.log(DB_LINK)
}
else {
return DB_LINK
}
}
在index.js级别,我必须将ReactDOM.render包装在异步范围内,以便在呈现组件之前等待set_DB_LINK函数调用(以确保在任何组件中使用“DB_LINK”之前填充它)
//修改前的index.js
ReactDOM.render(
,document.getElementById('root'))
);
//修改后的index.js
(
异步()=>{
等待set_DB_LINK().catch(err=>console.log(err))
ReactDOM.render(
,document.getElementById('root'))
);
}
)()
我想知道这是好的做法还是坏的做法;在后一种情况下,我想了解它将如何影响我的网站的生命周期/性能/呈现
谢谢你的帮助
//index.js before my modification
ReactDOM.render(
<Router routes={routes} history={hashHistory} />, document.getElementById('root')
);
//index.js after my modification
(
async () => {
await set_DB_LINK().catch(err => console.log(err))
ReactDOM.render(
<Router routes={routes} history={hashHistory} />, document.getElementById('root')
);
}
)()