首页 > 解决方案 > 如何在 React js 中获取和显示数据但第 26 行:'cusList' is not defined no-undef 错误即将出现,请 heap.tnx

问题描述

如何使用 React js 在 ASP.net 核心中获取和显示数据 第 26 行:'cusList' is not defined no-undef 错误即将出现。

import React, { Component } from 'react';
import './Map';

export class FetchCustomer extends Component {
    static displayName = FetchCustomer.Name;

    constructor(props) {
        super(props);
        this.state = { customers: [], loading: true };
    }

    render() {
        let contents = this.state.loading
            ? <p><em>Loading...</em></p>
            : this.renderCustomerTable(this.state.cusList);
        return <table className='table'>
            <thead>
                <tr>
                    <th></th>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Address</th>
                </tr>
            </thead>
            <tbody>
                {cusList.map(cus =>
                    <tr key={cus.Id}>
                        <td></td>
                        <td>{cus.Id}</td>
                        <td>{cus.Name}</td>
                        <td>{cus.Address}</td>
                        <td>
                            <a className="action" onClick={(id) => this.handleEdit(cus.Id)}>Edit</a>  |
                            <a className="action" onClick={(id) => this.handleDelete(cus.Id)}>Delete</a>
                        </td>
                    </tr>
                )}
            </tbody>
        </table>;

        fetch('api/Customer/Index')
            .then(response => response.json())
            .then(data => { this.setState({ cusList: data, loading: false }) });

    }
}

标签: fetch

解决方案


您的代码需要进行以下更改...

在您的构造函数中,使用以下代码更改最后一行代码:

this.state = { customers: [], loading: true, cusList: [] };

在“tbody”部分,请将代码更改为:

<tbody>
            {this.state.cusList.map(cus =>
                <tr key={cus.Id}>
                    <td></td>
                    <td>{cus.Id}</td>
                    <td>{cus.Name}</td>
                    <td>{cus.Address}</td>
                    <td>
                        <a className="action" onClick={(id) => this.handleEdit(cus.Id)}>Edit</a>  |
                        <a className="action" onClick={(id) => this.handleDelete(cus.Id)}>Delete</a>
                    </td>
                </tr>
            )}
</tbody>

这应该有效。此外,从错误本身可以清楚地看出您缺少什么。希望能帮助到你。


推荐阅读