React点击ListGroup.Item传递userid为undefined的解决方案求助
解决React中ListGroup.Item点击时无法获取userid的问题
我帮你梳理下代码里的几个关键问题,然后给出完整的修复方案:
问题分析
- 事件参数接收不匹配:你在
onClick里通过bind(this, User.userid)传递了用户ID,但handleclick函数里把参数命名为User,还试图读取User.userid——实际上传过来的已经是userid本身了,这就导致你拿到的是undefined。 - State访问方式错误:
console.log(this.Id)是错误的,要访问组件状态里的Id,必须用this.state.Id;而且setState是异步操作,直接在它后面打印拿不到最新值。 - Axios请求写法错误:
axios.post的第二个参数是请求体数据,请求头应该放在第三个参数的配置对象里,你现在把headers放进了请求体,会导致接口请求失败或者拿不到正确的用户列表。 - 路由跳转时机错误:因为
setState异步,你在调用setState后立刻跳转路由,目标组件可能无法获取到更新后的Id,应该把跳转放在setState的回调函数里。
修复后的完整代码
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) } // 修改参数名为userid,匹配传递过来的ID值 handleclick = (userid) => { this.setState({ Id: userid }, () => { // 在setState回调里执行跳转,确保state已更新 this.props.history.push('/Viewuserbyid') // 此时能拿到最新的state值 console.log(this.state.Id); }) } componentDidMount() { const headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', } // 修正axios.post参数:将headers放在配置项中,而非请求体 axios.post('https://localhost:/api/getallusers', {}, { headers: headers }) .then(res => { console.log(res) this.setState({ User: res.data }) }) .catch(error => { this.setState({ error: 'Error retrieving data' }) console.log(error) }) } render() { const { User, error } = this.state; return ( <div style={{ height: "100%" }}> <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
额外优化建议
- 变量命名尽量统一:比如你有的地方用
User,有的地方用user,建议非组件名的变量用小写开头,避免混淆。 - 接口请求规范:如果
getallusers接口不需要提交数据,建议把axios.post改成axios.get,更符合RESTful规范,写法为axios.get('https://localhost:/api/getallusers', { headers: headers })。 - 路由传参优化:传递Id到目标组件
Viewuserbyid时,也可以直接通过路由参数传递,比如this.props.history.push(/Viewuserbyid/${userid}),目标组件可通过props.match.params.userid直接获取,无需依赖父组件state,更灵活。
内容的提问来源于stack exchange,提问作者Arvind Udayashankar
相关产品推荐
相关产品推荐

