【发布时间】:2018-02-07 12:13:35
【问题描述】:
尽管最近严重缺乏 Javascript 经验,但我一直在尝试学习 React,但遇到了一些意想不到的障碍。我正在重写我的个人网站(基本上是静态 HTML,后端有一些 PHP),我想做的一件事是从外部 JSON 文件加载我的简历的详细信息(下一步是从一个静态 JSON 文件,用于调用将返回数据的端点)。
在我的简历中,我列出了几项工作的成就,其中一些我想返回少量标记(在一种情况下,一个指向我是发明人的专利的链接)另一个只是将样式应用于单个句子以引起人们对一些无偿工作的注意)。我知道我可以使用 React 中的 dangerouslySetInnerHTML() 方法来传递包含标记的字符串并对其进行渲染......但我似乎无法让它工作。
这里是有问题的组件:
import React, {Component} from 'react';
class WorkEntry extends Component {
constructor(props) {
super(props);
var _this = this;
this.usedSkillsTags = [];
this.responsibilitiesTags = [];
this.achievementsTags = [];
this.props.technologiesUsed.forEach(function (item) {
_this.usedSkillsTags.push(<li>{item}</li>)
});
this.props.responsibilities.forEach(function (item) {
_this.responsibilitiesTags.push(<li>{item}</li>)
});
this.props.achievements.forEach(function (item) {
if(item.indexOf("<") > -1 && item != null ) {
_this.achievementsTags.push(<li dangerouslySetInnerHTML={ { _html : item.toString() } }/>)
}
else{
_this.achievementsTags.push(<li>{item}</li>)
}
});
}
render() {
return (
<div>
<div class="row">
<div class="well">
<div class="row">
<div class="col-sm-12">
<h3>{this.props.companyName} -
<small> {this.props.jobTitle}</small>
</h3>
</div>
</div>
<div class="row">
<div class="col-sm-12">{this.props.startDate} - {this.props.endDate}</div>
</div>
<div class="row">
<div class="col-sm-4">
<h4 class="text-center">Skills Used</h4>
<ul class="wrapped-list">
{this.usedSkillsTags}
</ul>
</div>
<div class="col-sm-8">
<h4 class="text-center">Responsibilities</h4>
<ul>
{this.responsibilitiesTags}
</ul>
</div>
</div>
{ this.achievementsTags.length > 0 &&
<div class="row">
<div class="col-sm-12">
<h4 class="text-center">Notable Projects and Achievements</h4>
<ul>
{this.achievementsTags}
</ul>
</div>
</div>
}
</div>
</div>
</div>
);
}
}
export default WorkEntry;
这是导致问题的 Json:
{
"companyName": "Eloquence Communications",
"jobTitle": "Lead Developer",
"startDate": "January 2013",
"endDate": "February 2014",
"technologiesUsed": [
"Java",
"SQL",
"Idea",
"Bamboo",
"Nexus",
"Maven",
"Git",
"JavaFX",
"Python"
],
"responsibilities": [
"Designed overall architecture for hospital Nurse Call System",
"Managed complex build process for multiple Java applications using Git, Maven, Nexus, and Bamboo",
"Proposed idea which was eventually patented by employer",
"Lead a small team of developers to convert an idea into a product"
],
"achievements": [
"After proposing a method of nursing staff tracking and authentication using NFC, was named as an inventor on <a href='http://patents.justia.com/patent/20140330575'>patent application #20140330575</a>"
]
}
我显然已经阅读了错误消息中的链接,但我看不出文档中的代码与我自己的代码之间没有区别。任何人都可以在这里提供一些专业知识吗?
【问题讨论】:
-
Offtopic
item.indexOf("<") > -1 && item != null第二次检查为时已晚。试图读取 null 或 undefined 的属性会抛出异常。
标签: javascript json reactjs