我正在尝试从JSON文件中提取特定值。我将数据附加到组件,然后通过getProjectsList函数传递该函数,然后该函数应查找特定的JSON文件并在列表项中呈现该数据。
这是我的组件
class OpenProjectsHome extends React.Component {
constructor () {
super();
this.getProjectList = this.getProjectList.bind(this);
}
getProjectList(project) {
var projectNameFile = openProjectsData[project]
var url = window.location.protocol + "//" + window.location.host + "/open-projects/" + projectNameFile;
let clientName = "";
let projectName = "";
var startDate = "";
var component = this;
var jqxhr = $.get( url, function(myData) {
// console.log(myData)
console.log(myData[0].Client)
console.log(myData[0].Project)
console.log(myData[0].StartDate)
clientName = myData[0].Client
projectName = myData[0].Project
startDate = myData[0].StartDate
})
.fail(function() {
alert( "error" );
});
var projectURL = "project?=" + projectName;
return (
<li>
<a href={projectURL} title="">
<h6 className="eyebrow">{clientName}</h6>
<h6>{projectName}</h6>
<span><strong>Started:</strong> {startDate}</span>
</a>
</li>
)
}
render() {
return(
<section className="project-lists project-lists--current">
<div className="panel">
<div className="panel__header">
<h4 className="panel__title">Open Projects</h4>
</div>
<div className="panel__content">
<ul className="unordered-list">
{/* /////
///// WORKS
///// */}
{Object.keys(this.props.data).map(this.getProjectList)}
</ul>
</div>
</div>
</section>
);
}
}
它渲染了两个<li>
,但是我的变量clientName
,ProjectName
,StartDate
在返回值($中的console.log)中都渲染为null。开始工作)
任何帮助将不胜感激。
答案 0 :(得分:0)
您应该使用setState以及axios和arrow函数
var jqxhr =axios.get(url, (myData)=>{
// console.log(myData)
this.setState({
clientName : myData[0].Client,
projectName : myData[0].Project,
startDate = myData[0].StartDate
})
console.log(myData[0].Client)
console.log(myData[0].Project)
console.log(myData[0].StartDate)
})
.fail(function() {
alert( "error" );
});
axios doc https://github.com/axios/axios