reactjs 无法读取undefined的属性(阅读'setState'),Laravel-React

wnavrhmk  于 2023-05-17  发布在  React
关注(0)|答案(1)|浏览(148)

enter image description here

class Table extends Component {

    constructor(props) {
        super(props);
        
        this.state = {
            employee: [],
        }
    }
    //Life Sycle Methord
    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">Slary</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;

当我尝试这个代码(如上面提到的图像https://i.stack.imgur.com/gazFY.png),我得到一个错误如下...
“无法读取未定义的属性(阅读'setState')”

1bqhqjot

1bqhqjot1#

你可以直接在getEmployeeList中调用这个.setState..

constructor(props) {
    super(props);
    
    this.state = {
        employee: [],
    }
    this.getEmployeeList = this.getEmployeeList.bind(this);
}
async functiion getEmployeeList(e) {
    const response = await axios.get('get/employee/list');
        console.log(response.data);
        this.setState({
            employee : response.data,
        });
}

有没有什么特殊的原因,你把这个赋值给变量self。这个关键字在普通函数和箭头函数中的工作方式也不同。
参考..
How does the "this" keyword work, and when should it be used?

相关问题