【问题标题】:React import json dataReact 导入 json 数据
【发布时间】:2017-05-05 08:46:10
【问题描述】:

我使用 react vega 绘制图表。当我为图表编写配置时,它可以工作。我想从外部文件中获取 json 格式的配置 barChartConfig.json

我尝试导入此文件,但没有成功。我的问题是如何导入 json 并将其分配给变量?

import config from './barChartConfig.json';

const barSpec = config;
const Vega = ReactVega.default;

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            spec: barSpec
            // ,data: barData
        };
    }

    render() {
        return (
            <div>

                <Vega spec={this.state.spec} />

            </div>
        );
    }
}

const app = document.getElementById('app');

ReactDOM.render(<App />, app);

【问题讨论】:

标签: reactjs vega


【解决方案1】:

当你使用这个时: import config from './barChartConfig.json'; 这意味着您正在“要求”您的捆绑程序(webpack?)在创建 bundle.js 文件时包含此文件的数据。
当然,你需要一个合适的加载器,比如json-loader。
如果您试图在运行时获取这些数据,那么您需要通过 ajax 请求来获取它。 (fetch, axios 等...)

【讨论】:

    【解决方案2】:

    如果您使用 create-react-app,json-loader 将已包含在内。在这种情况下,您可以使用以下语句来加载 json 文件。

    var config = require('./barChartConfig.json');
    

    【讨论】:

      猜你喜欢
      • 2021-03-28
      • 2020-11-29
      • 2021-02-08
      • 2021-10-10
      • 2013-06-01
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多