【发布时间】:2017-08-15 14:00:45
【问题描述】:
我在使用 React 时搞砸了,从 本地文件 localhost 读取 json 时出现此错误。我检查了其他问题,但没有得到任何结果。我已经从 chrome 应用商店安装了 react 开发工具并检查了错误,所以我没有收到跨源错误。
代码如下:
class Content extends React.Component {
constructor(){
super();
this.state={
json: {
categories: []
}
};
}
componentWillMount(){
var _this = this;
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
this.serverRequest =
axios
.get(dir+"/data.json")
.then(function(result) {
// we got it!
_this.setState({
json:result
});
});
}
render() {
var title = <a>{this.state.json.title}</a>;
return (
<div>
<h2>Content</h2>
<h3>{title}</h3>
{this.state.json.categories.map(function(item) {
return (
<div key={item.categoryID} className="category">
<div> {item.categoryName} </div>
<div> {item.categoryDescridivtion} </div>
<div> {item.videosCount} </div>
</div>
);
})}
</div>
);
}
}
这是 JSON:
{
"categories": [{
"categoryID": "294",
"parentID": "304",
"subjectID": "7",
"categoryName": "Apps and Side Dishes (Laura)",
"categoryDescription": "Learn to make amazing appetizers and side dishes with Laura in the Kitchen.",
"videosCount": "101",
"forumCategoryID": "163"
}, {
"categoryID": "285",
"parentID": "304",
"subjectID": "7",
"categoryName": "Side Dishes",
"categoryDescription": "Side dish recipes for salads, vegetables, sauces with Hilah cooking.",
"videosCount": "38",
"forumCategoryID": "163"
}, {
"categoryID": "337",
"parentID": "304",
"subjectID": "7",
"categoryName": "Side Dishes (bt)",
"categoryDescription": "Side dish recipes with Byron Talbott.",
"videosCount": "5",
"forumCategoryID": "163"
}, {
"categoryID": "301",
"parentID": "304",
"subjectID": "7",
"categoryName": "Side Dishes for Barbecue",
"categoryDescription": "Barbecue side dish recipes done on the grill by the BBQ Pit Boys!",
"videosCount": "43",
"forumCategoryID": "163"
}, {
"categoryID": "297",
"parentID": "304",
"subjectID": "7",
"categoryName": "Soups and Salads (Laura)",
"categoryDescription": "Looking for the perfect recipe to start your meal? Or are you looking to eat something on the lighter side? These are sure to have you covered!",
"videosCount": "70",
"forumCategoryID": "163"
}],
"title": "Title page"
}
这是来自调试控制台的关于 axios 调试控制台结果的输出:
【问题讨论】:
-
当您提出问题时,文本区域右侧有一个橙色的大如何格式化框,其中包含有用的信息。还有一个完整的格式化辅助工具栏。还有一个 [?] 按钮提供格式化帮助。 并且一个预览区域位于文本区域和发布您的问题按钮之间(这样您就必须滚动过去才能找到该按钮,以鼓励您查看它)显示您的帖子发布时的样子。使您的帖子清晰,并证明您花时间这样做,可以提高您获得好答案的机会。
-
这次我已经为你修好了。
标签: javascript json reactjs react-jsx axios