在React中导入JSON文件

JavaScript React.js

西门Near

2020-03-18

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

找不到模块“ ./customData.json”

有人可以帮我吗?如果我的DATA变量位于index.js外部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

第2037篇《在React中导入JSON文件》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
猿古一梅 2020.03.18

尝试export default DATAmodule.exports = DATA

GilTony泡芙 2020.03.18

请存储扩展名为.js的JSON文件,并确保JSON应位于同一目录中。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android