2016-09-25 37 views
6

我是React的新手,我試圖從外部文件導入JSON DATA變量。我收到以下錯誤:在React中導入JSON文件

Cannot find module "./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 

在此先感謝!

回答

2

嘗試export default DATAmodule.exports = DATA

+0

不能正常工作:(!!謝謝 –

+0

uhm你有沒有試過用require而不是import?但是我確定這不是問題,路徑是否正確?哦,並且試着寫入import DATA而不是customData。 – Salvatore

+0

Import DATA works !!非常感謝!!:D –

3

請存儲您的JSON文件與擴展名爲.js,並確保您的JSON應該在同一目錄中。

+0

已解決!!謝謝你的回答!! –

7

一個很好的方法(不添加假的.js擴展名,代碼不適用於數據和配置)是使用json-loader模塊。如果你已經使用create-react-app腳手架項目,該模塊已經包含了,你只需要導入您的JSON:

import Profile from './components/profile'; 

This答案詳細解釋。

+0

奇怪。當我嘗試在'create-react-app'中導入一個json文件時,它返回'undefined ' – arvinsim