【问题标题】:Render json is not defined in ReactReact 中未定义渲染 json
【发布时间】:2017-08-16 17:13:52
【问题描述】:

谁能在 react-js 上下文中向我解释以下场景: 我使用 webpack 并使用预设“babel-preset-env”和“react”。

在一个文件的顶部,我导入了一个 config.json,我尝试使用开发人员工具和调试器语句进行检查。

console.log 按预期记录一组对象。如果我进入 developer-tools js-console 并输入 CONFIG,我会收到 Uncaught ReferenceError: CONFIG is not defined。

import React, { Component } from 'react';
import CONFIG from './config.json';

class MyComponent extends Component{
    render(){
        //this statement logs as expected
        console.log(CONFIG);

        // the debugger stops execution, but when I enter CONFIG in the
        // dev-tools Console I get the error: Uncaught ReferenceError: 
        // CONFIG is not defined
        debugger;
    }
}

非常感谢任何帮助。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    CONFIG 在您正在编写的模块中定义。它不是真正的全局变量,它只是该模块(即该文件)内部的“全局”变量。

    如果您真的想让它在浏览器中全局可用,请尝试添加window.CONFIG = CONFIG

    【讨论】:

    • 谢谢!那是个很好的观点。当我将配置添加到类构造函数中的模块时,我可以设法访问配置 this.config = config.但是为什么console.log 可以访问CONF 变量呢?
    • console.log 可以“看到”它,因为它CONFIG 的范围内(即在模块内)运行。如果您在不同的模块/文件/组件中尝试console.log(CONFIG),它将失败:可能会打印undefined 或抛出相同的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 2017-10-23
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多