javascript - 如何将 api 响应值传递给 onclick 函数
问题描述
当我单击 listgroup.item 时,我希望将用户 ID 传递给 onclick 函数,我得到的值为 undefined。如果我在 handleclick 中获取值,我会将值作为道具传递给另一个组件并获取完整的详细信息用户。任何解决方案提前感谢
import React, { Component } from 'react'
import axios from 'axios'
import ListGroup from 'react-bootstrap/ListGroup';
class ViewUsers extends Component {
constructor(props) {
super(props)
this.state = {
User:[],
error:[],
Id:0
}
this.handleclick = this.handleclick.bind(this)
}
handleclick = (User) => {
this.setState({
Id:User.userid
})
this.props.history.push('/Viewuserbyid')
console.log(this.Id);
}
componentDidMount(){
const header ={
'Content-Type': 'application/json',
'Accept': 'application/json',
}
axios.post('https://localhost:/api/getallusers',{
header:header
})
.then(res => {
console.log(res)
this.setState({
User:res.data
})
})
.catch(Error =>{
this.setState({
error:'Error retriving data'
})
console.log(Error)
})
}
render() {
const {User,error} = this.state;
return (
<div style={{height:"100%"}}>
{/* onChange={(event)=>this.setState({keyword:event.target.value})} */}
<input type="text" placeholder="search" className="form-control form-control-sm" />
<button>search</button>
{
User.length ? User.map(User => (
<ListGroup key={User.userid}>
<ListGroup.Item onClick={this.handleclick.bind(this,User.userid)}>
Name : {User.name} <br/> AccountNumber : {User.accountNumber}
</ListGroup.Item>
</ListGroup >) : null
}
{
error ? <div>{error}</div> : null
}
</div>
)
}
}
export default ViewUsers
解决方案
这行得通吗?
<ListGroup.Item onClick={() => this.handleclick(User.userid)}>
也许在点击处理程序中使用它:
handleclick = (User) => {
this.setState({
Id:User.userid,
// might want to update User also by uncommenting the next line
// User,
}, () => {
console.log(this.state.Id)
console.log(this.state.User)
})
this.props.history.push('/Viewuserbyid')
}
推荐阅读
- amazon-web-services - 我可以在没有网关 API 的情况下直接调用 AWS Lambda 吗?
- java - 使用 HTTPs 调用 GET 中的 @RequestParam 始终为空
- visual-studio - VS 2010 无法连接 AzureDevops server 2019 中的项目
- mysql - 如何使用 MySQL 获得类似数据透视表的结果
- angular - 升级到 Angular 8.3.5 后,Angular 应用程序不加载应用程序模块/组件
- python - 如何将变量作为 url 的一部分?
- python-2.7 - 从 API 触发 ansible playbook 并在后台运行它们
- django - 来自 ListBox 的数据发布未呈现到数据库
- c# - 如何更新注释的内容
- angular - 反应式开发 | RxJS 异步管道不工作