我正在尝试将以下代码返回到屏幕上。一切正常,但我无法从JobDisplayFunction返回由其父函数返回的数组,因此进入render()
async renderJobs(){
//do stuff
this.apiclient.getJobsByEmployer('', async (error, returnVal) => {
var job = returnVal
console.log('job')
console.log(job) //prints
console.log('returnVal')
console.log(returnVal) //prints
jobDisplayFunction(job)
})
const jobDisplayFunction = function(job){
var array = []
job.forEach(function(result){
console.log(result)
if(result.active){
array.push(
<div className='sample'>
<Image src={profilePicture} height={50} width={50} alt='Employer Logo' rounded/>
<h2>{result.title}</h2>
<p>{result.location}</p>
<p>{result.sector}</p>
<p>{result.county + ', ' + result.country}</p>
<p>{'Paid: ' + result.compensation}</p>
<p>{'Total Applicants: ' + result.applicants}</p>
<p>{'Shortlisted: ' + result.shortlist}</p>
<p>{'Interviews: ' + result.interview}</p>
<p>{'Offered Job: ' + result.offer}</p>
<p>{'Accepted Job: ' + result.accepted}</p>
<p>{'Rejected Job: ' + result.rejected}</p>
<Button onClick={() => this.getJobIndex(result.active, result.id)}>duplicate</Button>
</div>
);
}
}.bind(this))
// return(array)
return array
}
}
答案 0 :(得分:0)
当调用异步函数时,它返回一个Promise,或者是一个已实现的Promise或一个被拒绝的Promise。
我建议在componentDidMount()中调用this.renderJobs()并将数据设置为你的状态并在render()中呈现状态,看起来像这样:
componentDidMount() {
this.renderJobs().then( (array) => {
this.setState({ jobs: array });
});
}
render() {
if (!this.state.jobs) {
return null;
}
return (<div>{this.state.jobs}</div>);
}
修改强>
componentDidMount() {
this.apiClient...().then( (returnVal) => {
this.setState({ jobs: returnVal });
});
}
render() {
if (!this.state.jobs) {
return null;
}
return <div>{this.jobDisplayFunction(this.state.jobs)}</div>;
}
jobDisplayFunction = (jobs) => {
...same as before
};