简体   繁体   中英

Global variable within export function not accessible

I would like update a variable in case the user set the language manually in a web interface (ReactJS). However I cannot access that variable in my export function.

I tried already to use different combinations of "export" (also for the variable), but nothing worked.

File: index.js


export function getLanguage() {

  console.log(languageManuallySelected);

}

Expected result: false

Actual result: undefined

The issue is that the variable languageManuallySelected is not defined in the scope of the function you are exporting. To fix this, you need to export the enclosing function with languageManuallySelected in its scope. A very generic example would look like this

export function someFunction () {
    languageManuallySelected = false;
    function getLanguage() {
        console.log(languageManuallySelected);
    }
}

To call it

import someFunction from './someFile';
someFunction.getLanguage(); 

should print 'false'

There is not enough context in your question, but I will try to guess.

Maybe you need to refer window as a global scope to access your variable:

export function getLanguage() {

    console.log(window.languageManuallySelected);

}

The only thing that can be assumed is a wrong pathname.

Or you are not simply destructuring the func whilst importing.

At FIRST GLANCE I CAN ONLY BE ASSUMED LIKE THIS, SINCE YOU HAVEN'T PROVIDED THE RELEVANT CODES..

A live example'd be,

folder: services/utils

export const getValueArray = data => data.map(item => item.value)

and now you should import to the desired file

import { getValueArray } from '--correct_path_name'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM