我是新手,我正在try 从外部文件导入JSON DATA变量.我发现以下错误:

找不到模块"./customData.json"

谁能帮帮我吗?如果我在index.js中有DATA变量,它就可以工作,但如果它在外部JSON文件中,它就不能工作.

index.js
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import customData from './customData.json';
import Profile from './components/profile';
import Hobbies from './components/hobbies';

class App extends Component {
  render() {
    return (
      <div>
        <Profile name={this.props.profileData.name}imgUrl={this.props.profileData.imgURL} />
        <Hobbies hobbyList={this.props.profileData.hobbyList}/>
      </div>
    );
  }
}

ReactDOM.render(<App profileData={DATA}/>, document.querySelector('.container'));
hobbies.js
import React, {Component} from 'react';

var Hobbies = React.createClass({
  render: function(){
    var hobbies = this.props.hobbyList.map(function(hobby, index){
        return (<li key={index}>{hobby}</li>);
    });
    return (
        <div>
            <h5>My hobbies:</h5>
            <ul>
                {hobbies}
            </ul>
        </div>
    );
  } 
});

export default Hobbies;
profile.js
import React from 'react';

var Profile = React.createClass({
render: function(){
    return (
        <div>
            <h3>{this.props.name}</h3>
            <img src={this.props.imgUrl} />
        </div>
    )
  }
});

export default Profile
customData.json
var DATA = {    
    name: 'John Smith',
    imgURL: 'http://lorempixel.com/100/100/',
    hobbyList: ['coding', 'writing', 'skiing']
}

export default DATA

推荐答案

一个很好的方法(不添加假的.js扩展名,用于代码而不是数据和配置)是使用json-loader模块.如果您已经使用create-react-app构建了您的项目,那么该模块已经包含在内,您只需要导入json:

import Profile from './components/profile';

This答案解释了更多.

Json相关问答推荐

Vega-Lite时钟(使用Vega-Lite中的计时器)

NiFi QueryRecord处理器- Select 可选的JSON属性

解析Ansible AWS ec2_security_group中的json以提取安全组ID

Powershell ConvertFrom-Json 意外地从包含字符串的单个项目数组生成字符串而不是对象数组

使用 Power BI 中的 Deneb 视觉效果绘制面积图中的 X 轴日期

使用不同行数的数据创建嵌套Jolt

每次在 SoapUI 中发送请求时,将 JSON 响应的子 node 分配给项目变量

Powershell v7 文本背景突出显示

JQ 中的样本标准偏差

通过sql查询读取嵌套Json

在循环中将变量添加到 bash 数组

如何使用 jq 返回此 JSON 文件的文本字段?

Golang / Go - 如果 struct 没有字段,如何将其编组为空?

将 js Array() 转换为 JSON 对象以用于 JQuery .ajax

获取json中某个键的索引

将json字符反序列化为枚举

是否可以将数据写入本地 json 文件,除了Angular 之外什么都没有?

如何在 JAVA 中对 JSONArray 进行排序

无法将 System.String 转换或转换为 Class 对象

不处理从这里抛出的错误