Laravel-React项目中出现Cannot read properties of undefined (reading 'setState')错误求助
问题描述
在Laravel-React项目中编写了如下Table组件代码:
class Table extends Component { constructor(props) { super(props); this.state = { employee: [], } } //Life Cycle Method componentDidMount() { this.getEmployeeList(); } // Get Employee List getEmployeeList = (e) => { axios.get('get/employee/list').then(function (response) { console.log(response.data); this.setState({ employee : response.data, }); }) } render() { return ( <div className="container"> <div className="row justify-content-center"> <div className="col-md-8"> <div className="card"> <table className="table table-hover"> <thead> <tr> <th scope="col" width="100px">#</th> <th scope="col" width="100px">Name</th> <th scope="col" width="100px">Salary</th> <th scope="col" width="100px">Action</th> </tr> </thead> <tbody> {this.state.employee.map(function (x, i) { <TableRow key={i} data={x} /> })} </tbody> </table> </div> </div> </div> </div> ); } } export default Table;
运行时出现错误:Cannot read properties of undefined (reading 'setState'),请帮忙解决。
解决方法
1. 修复setState的this指向问题
错误核心是axios回调里的普通函数改变了this的指向,此时this不再指向组件实例,无法调用this.setState,有两种修复方式:
方式一:使用箭头函数
箭头函数不会绑定自身的this,会继承外层作用域的this,直接替换回调函数即可:
getEmployeeList = (e) => { axios.get('get/employee/list').then((response) => { console.log(response.data); this.setState({ employee : response.data, }); }) }
方式二:提前保存组件实例的this
在axios请求前把组件的this存到变量中,回调里使用该变量调用setState:
getEmployeeList = (e) => { const self = this; axios.get('get/employee/list').then(function (response) { console.log(response.data); self.setState({ employee : response.data, }); }) }
2. 修复表格行渲染的返回问题
另外你的map方法中没有返回TableRow组件,会导致表格无数据行显示,需要补充返回逻辑:
{this.state.employee.map(function (x, i) { return <TableRow key={i} data={x} /> })}
或用箭头函数简化写法:
{this.state.employee.map((x, i) => <TableRow key={i} data={x} />)}
内容的提问来源于stack exchange,提问作者Chenaya Ruheli
相关产品推荐
相关产品推荐

