我是React的新手,正在尝试DATA从外部文件导入JSON 变量。我收到以下错误:
DATA
找不到模块“ ./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
一种不错的方法(不添加伪造的.js扩展名,用于代码而不用于数据和配置)是使用json-loader模块。如果您曾经使用create-react- app过脚手架,那么该模块已经包含在内,您只需导入json:
json-loader
create-react- app
import Profile from './components/profile';