Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

reactjs - How to declare a global variable in React?

I initialized i18n translation object once in a component (a first component that loads in the app ). That same object is required In all other components. I don't want to re-initialize it in every component. What's the way around? Making it available to window scope doesn't help as I need to use it in the render() method.

Please suggest a generic solution for these problems and not i18n specific solution.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Beyond React

You might not be aware that an import is global already. If you export an object (singleton) it is then globally accessible as an import statement and it can also be modified globally.

If you want to initialize something globally but ensure its only modified once, you can use this singleton approach that initially has modifiable properties but then you can use Object.freeze after its first use to ensure its immutable in your init scenario.

const myInitObject = {}
export default myInitObject

then in your init method referencing it:

import myInitObject from './myInitObject'
myInitObject.someProp = 'i am about to get cold'
Object.freeze(myInitObject)

The myInitObject will still be global as it can be referenced anywhere as an import but will remain frozen and throw if anyone attempts to modify it.

My hack of global state using a singleton

https://codesandbox.io/s/react-typescript-playground-forked-h8rpu

If using react-create-app

(what I was looking for actually) In this scenario you can also initialize global objects cleanly when referencing environment variables.

Creating a .env file at the root of your project with prefixed REACT_APP_ variables inside does quite nicely. You can reference within your JS and JSX process.env.REACT_APP_SOME_VAR as you need AND it's immutable by design.

This avoids having to set window.myVar = %REACT_APP_MY_VAR% in HTML.

See more useful details about this from Facebook directly:

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...