我有一个 if 条件会改变状态值,而 else 部分为状态分配一个不同的值。但两者都被处决。如何避免这种情况。
getJobId = (event) => {
const { appliedjobs } = this.props
{appliedjobs && appliedjobs.map(job => {
if(event.target.getAttribute('name')===job.id)
{
this.setState({applystatus:job.applystatus},()=>{
console.log('====================================');
console.log(this.state.applystatus);
console.log('====================================');
})
}
else if(event.target.getAttribute('name')!=job.id){
this.setState({applystatus:"apply now"},()=>{
console.log('====================================');
console.log("else ",this.state.applystatus);
console.log('====================================');
})
}
})}
this.setState({
jobid: event.target.getAttribute('name')
}, () => this.sendJobId())
}
您正在映射applidjobs
数组,并在每次迭代期间在语句的state.applystatus
两个分支中进行设置if
。因此,该applystatus
值将是最后一次迭代期间设置的值:
appliedjobs.map(job => {
if (event.target.getAttribute('name') === job.id) {
this.setState({ applystatus: job.applystatus })
} else if (event.target.getAttribute('name') != job.id) {
this.setState({ applystatus: 'apply now' })
}
})
this.setState({ jobid: event.target.getAttribute('name') }, () => this.sendJobId())
我建议寻找与name
属性匹配的作业,如果找到,将 设置applystatus
为作业的状态,否则将其设置为apply now
,您不需要映射或使用if/else
语句:
const jobid = event.target.getAttribute('name');
const job = appliedjobs.find(({ id }) => id === jobid );
this.setState({
applystatus: job ? job.applystatus : 'apply now,
jobid
}, () => this.sendJobId());
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句