如何在JSX中获取数据并加载到页面上?

问题描述 投票:0回答:1

我正在尝试将ASP.NET core与react和jsx一起使用,到目前为止,我已经能够获取数据,但是当我运行FetchCustomer.tsx时,它是空的。

这是控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ICTask1.Models;

namespace ICTask1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CustomersController : ControllerBase
{
    private readonly DBContext _context;

    public CustomersController(DBContext context)
    {
        _context = context;
    }

    // GET: api/Customers
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Customer>>> GetCustomer()
    {
        return await _context.Customer.ToListAsync();
    }

    // GET: api/Customers/5
    [HttpGet("{id}")]
    public async Task<ActionResult<Customer>> GetCustomer(int id)
    {
        var customer = await _context.Customer.FindAsync(id);

        if (customer == null)
        {
            return NotFound();
        }

        return customer;
    }

    // PUT: api/Customers/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see https://aka.ms/RazorPagesCRUD.
    [HttpPut("{id}")]
    public async Task<IActionResult> PutCustomer(int id, Customer customer)
    {
        if (id != customer.ID)
        {
            return BadRequest();
        }

        _context.Entry(customer).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!CustomerExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
    }

    // POST: api/Customers
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see https://aka.ms/RazorPagesCRUD.
    [HttpPost]
    public async Task<ActionResult<Customer>> PostCustomer(Customer customer)
    {
        _context.Customer.Add(customer);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetCustomer", new { id = customer.ID }, customer);
    }

    // DELETE: api/Customers/5
    [HttpDelete("{id}")]            
    public async Task<ActionResult<Customer>> DeleteCustomer(int id)
    {
        var customer = await _context.Customer.FindAsync(id);
        if (customer == null)
        {
            return NotFound();
        }

        _context.Customer.Remove(customer);
        await _context.SaveChangesAsync();

        return customer;
    }

    private bool CustomerExists(int id)
    {
        return _context.Customer.Any(e => e.ID == id);
    }
}}

这是我的FetchCustomer.tsx

import * as React from 'react';
import { RouteComponentProps } from 'react-router';
import { Link, NavLink } from 'react-router-dom';

interface FetchCustomerData {
customerList: CustomerData[];
loading: boolean;
}

export class FetchCustomer extends React.Component<RouteComponentProps<any, any>, FetchCustomerData> {

constructor(props: any) {
    super(props);
    this.state = { customerList: [], loading: true };
    fetch('api/Customers')
        .then(response => response.json() as Promise<CustomerData[]>)
        .then(data => {
            this.setState({ customerList: data, loading: true });
        });

    this.handleDelete = this.handleDelete.bind(this);
    this.handleEdit = this.handleEdit.bind(this); 
}

public render() {
    let contents = this.state.loading
        ? <p><em>Loading...</em></p>
        : this.renderCustomerTable(this.state.customerList);

    return <div>
        <p>
            <Link to="api/Customer">Create New</Link>
        </p>
        {contents}
    </div>;
}

//Delete
private handleDelete(id: number) {
    if (!confirm("Are you sure?" + id))
        return;
    else {
        fetch('api/Customers/5/' + id, {
            method: 'delete'
        }).then(data => {
            this.setState(
                {
                    customerList: this.state.customerList.filter((rec) => {
                        return (rec.customerId != id);
                    })
                });
        });
    }
}

private handleEdit(id: number) {
    this.props.history.push('api/Customers' + id);
}

private renderCustomerTable(customerList: CustomerData[]) {

    return <table className='table'>
        <p>This is table</p>
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Address</th>
                <th>Action</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            {
                customerList.map(cust =>
                    <tr key={cust.customerId}>
                    <td></td>
                        <td>{cust.name}</td>
                        <td>{cust.address}</td>
                        <td>
                            <a className="action" onClick={(id) => this.handleEdit(cust.customerId)}>Edit</a>  |
                        <a className="action" onClick={(id) => this.handleDelete(cust.customerId)}>Delete</a>
                        </td>
                        </tr>
            )}
        </tbody>
    </table>;

}

}

export class CustomerData {
customerId: number = 0;
name: string = "";
address: string = "";
}

客户控制器中的API正常工作,这里是输出。我在FetchCustomer中使用过api / Customers。

当我运行项目时,没有错误页面可以正常加载,但看不到数据

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9jamw0bi5wbmcifQ==” alt =“在此处输入图像描述”>

当我运行FetchCustomer时,我得到了这个

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9pZmppNC5wbmcifQ==” alt =“在此处输入图像描述”>

reactjs asp.net-core react-router
1个回答
0
投票

承诺的实际数据将在response.data下。尝试提供以下代码。

this.setState({ customerList: data.data, loading: true });
© www.soinside.com 2019 - 2024. All rights reserved.