我是React的新手,我正在尝试从外部文件导入JSON DATA变量.我收到以下错误:
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 (
);
}
}
ReactDOM.render(, 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 (
{hobby});});
return (
My hobbies:
{hobbies}
);
}
});
export default Hobbies;
profile.js
import React from 'react';
var Profile = React.createClass({
render: function(){
return (
{this.props.name}
)
}
});
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答案解释更多.
标签:javascript,json,reactjs
来源: https://codeday.me/bug/20190926/1821544.html