在React中导入JSON文件 [英] Import JSON file in React

查看:2315
本文介绍了在React中导入JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是React的新手,我正在尝试从外部文件导入JSON DATA 变量。我收到以下错误:

I'm new to React and I'm trying to import a JSON DATA variable from an external file. I'm getting the following error:


找不到模块./customData.json

Cannot find module "./customData.json"

有人能帮帮我吗?如果我在 index.js 中有 DATA 变量,但在外部JSON文件中没有,那么它可以工作。

Could some one help me? It works if I have my DATA variable in index.js but not when it's in an external JSON file.

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

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

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

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:

One nice way (without adding a fake .js extension which is for code not for data and configs) is to use json-loader module. If you have used create-react-app to scaffold your project, the module is already included, you just need to import your json:

import Profile from './components/profile';

回答更多解释。

这篇关于在React中导入JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆