【发布时间】:2021-10-27 06:26:00
【问题描述】:
我在 tsx 文件中有一个 React 组件和一些辅助方法。我想从global窗口对象初始化一些数据。
HTML 在head 内有一个script 标记,用于初始化数据,如下所示:
<head>
<script>
(function(global) {
'use strict';
global["my-app"] = {};
global["my-app"]["data"] = {
key1 : 'value1',
....
}
})(window);
</script>
</head>
<body>...</body>
全局数据中的一些字段在 React 组件和函数中使用。如果我从窗口对象中读取数据并在 React 组件内部进行初始化,那么我必须将字段 (a, b, c, d) 传递给各个方法。
import React from "react";
//other imports
const function1 = (a, b) => {
//uses a, b
}
const function2 = (a, d) => {
//uses a, d
}
export default function MyComponent(props: Props) {
const {a, b, c, d} = window["my-app"]["data"]
function f() {
//uses a and c
console.log(a + c);
//passes to other functions
function1(a, b)
...
function2(a, d)
}
}
相反,我可以将它移到 React 组件之外,以便它可以用于组件以及辅助函数,例如,
import React from "react";
//other imports
const {a, b, c, d} = window["my-app"]["data"]; //moved outside the component
const function1 = () => {
//uses a, b
}
const function2 = () => {
//uses a, d
}
export default function MyComponent(props: Props) {
//uses a, b and c
function f() {
//uses a and c
console.log(a + c);
function1()
...
function2()
}
}
我已经对此进行了测试,并且可以正常工作。但是,如果我将它移到组件之外,它会一直正确初始化吗? window["my-app"]["data"] 加载后是否可用?
【问题讨论】:
标签: reactjs