【发布时间】:2020-10-25 02:46:17
【问题描述】:
((React 新手))
我试图让不同的工作(上面列出的salary.job.id)在点击时通过。这些工作已经通过 axios 调用获得。 有没有更简单的方法来实现这一点?另外,调用 this.makesalary 两次是否正确(一次在 componentDidMount 中,另一次通过点击?
这就是我想要通过的东西
makesalary(slug = "charlotte") {
axios.get(`https://api.teleport.org/api/urban_areas/slug:${slug}/salaries/`)
.then(results => {
console.log(results)
const filteredata = results.data.salaries.filter(salary=>{
if(salary.job.id === "UX-DESIGNER"){
return true
}
if (salary.job.id === "WEB-DEVELOPER"){
return true
}
if(salary.job.id === "MOBILE-DEVELOPER"){
return true
}
return false
})
this.setState({salaries:
filteredata
})
}
)
}
这可以调用两次吗?位置是否正确?
componentDidMount (){
this.makesalary(this.props.slug)
}
_onclick(salary){
this.makesalary(salary.job.id)
}
这是渲染
<div>
<h2>What Tech Job are you in currently?</h2>
<CardGroup>
<Card>
<Card.Img variant="top" src= {Mobileicon} />
<Card.Body>
<Card.Title>Mobile Developer</Card.Title>
<Card.Text>
Mobile Developer specialise in mobile technology such as building apps for Google's Android, Apple's iOS and Microsoft's Windows Phone platforms.
</Card.Text>
</Card.Body>
<Card.Footer>
<Button variant="danger" onClick={this._onclick}>Pick this Job!</Button>{' '}
</Card.Footer>
</Card>
<Card>
<Card.Img variant="top" src= {UXicon} />
<Card.Body>
<Card.Title>UX Designer</Card.Title>
<Card.Text>
In a nutshell, the UX designer is responsible for how a product or website feels.
The UX designer's job is to zero in on users' underlying emotional and functional needs.
</Card.Text>
</Card.Body>
<Card.Footer>
<Button variant="danger" >Pick this Job!</Button>{' '}
</Card.Footer>
</Card>
<Card>
<Card.Img variant="top" src={Webdevelop} />
<Card.Body>
<Card.Title>Web Developer</Card.Title>
<Card.Text>
A Web Developer is responsible for the coding, design and layout of a website according to a company's specifications.
As the role takes into consideration user experience and function, a certain level of both graphic design and computer programming is necessary.
</Card.Text>
</Card.Body>
<Card.Footer>
<Button variant="danger" >
Pick this Job!</Button>{' '}
</Card.Footer>
</Card>
</CardGroup>
</div>
)
}
【问题讨论】:
-
如果你想通过 onClick 监听器传递一个参数,你需要传递一个封装的函数调用,即
onClick={()=>this._onclick(yourvalue)}。否则salary值实际上将是 React 传递的event对象 -
如果您想在组件安装后和每次单击按钮时调用该函数,则可以调用该函数两次。
标签: javascript reactjs api axios components