反应 - 在点击时遇到问题(反应)



((New to 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>

)

}

我想帮忙,所以我要指出一些事情,并提出一些建议。在开始之前,如果我说的话不正确,我必须道歉,如果有人纠正我,我将不胜感激。

我还假设您的makesalary函数已在上面定义(其中显示了 Axios 调用(。

在你的组件挂载方法中,你使用从props获得的参数调用makesalary 。如果你的道具是有效的,这绝对没问题。

您还碰巧在_onclick方法中调用makesalary。我建议你把它重命名为handleClickonClickHandler,以使其更清晰,并删除前面的_,因为它是不必要的(除非它是你正在使用的约定(。该方法本身看起来不错。

使用按钮调用_onclick时,请记住,它将event传递到方法中。您应该通过在按钮处传递一个函数(如() => _onclick(salary)(来onClick来处理此问题(因为您不打算将event用于任何操作(。除了正确处理事件外,这还可以帮助您传入正确的参数以进行_onclick。在您提供的代码片段中,似乎onClick没有将任何参数传递给_onclick函数。

我建议您阅读有关此内容的官方 React 文档: https://reactjs.org/docs/handling-events.html。

希望我有帮助!

编辑:如果您想知道,可以调用相同的方法两次!

最新更新