首页 > 解决方案 > 如何正确使用 ASP.NET Core Web Application React 项目模板

问题描述

不允许在标题中说帮助,但我需要帮助理解这个模板。我第一次尝试使用 ASP.NET Core Web Application React 项目模板。我已经对 React 有点熟悉,但不是这个项目模板。该模板带有一个小型天气 API,FetchData 页面向该 API 发出获取请求。

首先,我不知道 React 究竟从哪里发出请求,其次我不知道如何复制它。

这是获取数据方法:

获取数据

import React, { Component } from 'react';

export class FetchData extends Component {
  static displayName = FetchData.name;

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

  componentDidMount() {
    this.populateWeatherData();
  }

  static renderForecastsTable(forecasts) {
    return (
      <table className='table table-striped' aria-labelledby="tabelLabel">
        <thead>
          <tr>
            <th>Date</th>
            <th>Temp. (C)</th>
            <th>Temp. (F)</th>
            <th>Summary</th>
          </tr>
        </thead>
        <tbody>
          {forecasts.map(forecast =>
            <tr key={forecast.date}>
              <td>{forecast.date}</td>
              <td>{forecast.temperatureC}</td>
              <td>{forecast.temperatureF}</td>
              <td>{forecast.summary}</td>
            </tr>
          )}
        </tbody>
      </table>
    );
  }

  render() {
    let contents = this.state.loading
      ? <p><em>Loading...</em></p>
      : FetchData.renderForecastsTable(this.state.forecasts);

    return (
      <div>
        <h1 id="tabelLabel" >Weather forecast</h1>
        <p>This component demonstrates fetching data from the server.</p>
        {contents}
      </div>
    );
  }

  async populateWeatherData() {
    const response = await fetch('weatherforecast');
    const data = await response.json();
    this.setState({ forecasts: data, loading: false });
  }
}

除了这一行之外,这一切对我来说都很有意义:const response = await fetch('weatherforecast');. 我很难理解“天气预报”的确切位置。

现在这里是 WeatherForecast 控制器:

天气预报控制器

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ReactFront.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

这是我假设的类似 WeatherForecast 的模型类

WeatherForecast.cs

using System;

namespace ReactFront
{
    public class WeatherForecast
    {
        public DateTime Date { get; set; }

        public int TemperatureC { get; set; }

        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

        public string Summary { get; set; }
    }
}

这是获取的结果weatherforecast

天气预报

但是,我无法使用自己的控制器复制它。例如,我创建了这个简单的控制器:

值控制器

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

namespace ReactFront.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ValuesController : ControllerBase
    {
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "Value1", "Value2", "Value3" };
        }

        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "The vlaue is " + id;
        }
    }
}

并复制了这样的视图:

取值

import React, { Component } from 'react';

export class FetchValues extends Component {
    static displayName = FetchValues.name;

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

    componentDidMount() {
        this.populateValuesData();
    }

    static renderValuesTable(apiValues) {
        return (
            <table className='table table-striped' aria-labelledby="tabelLabel">
                <thead>
                    <tr>
                        <th>Value</th>
                    </tr>
                </thead>
                <tbody>
                    {apiValues.map(apiValues =>
                        <tr key={apiValues.value}>
                            <td>{apiValues.value}</td>
                        </tr>
                    )}
                </tbody>
            </table>
        );
    }

    render() {
        let contents = this.state.loading
            ? <p><em>Loading...</em></p>
            : FetchValues.renderValuesTable(this.state.apiValues);

        return (
            <div>
                <h1 id="tabelLabel" >Values from API</h1>
                <p>This component demonstrates fetching data from the server.</p>
                {contents}
            </div>
        );
    }

    async populateValuesData() {
        const response = await fetch('values');
        const data = await response.json();
        this.setState({ apiValues: data, loading: false });
    }
}

当我访问该FetchValues页面时,我收到此错误:

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0        fetch-values:1

并检查 Inspect -> Network -> Preview -> values (或 fetch-values) 预览为空。

以下是我的问题:

1.) 究竟在哪里weatherforecast,我如何看到它,以便我可以复制我的价值观正在发生的事情?

2.) 为什么预览中的值是空的?相同的代码在 API 项目模板中完美运行。

3.) 这个项目模板上是否有任何官方文档?我找不到超过 1 个无用的页面:https ://docs.microsoft.com/en-us/aspnet/core/client-side/spa/react?view=aspnetcore-5.0&tabs=visual-studio

标签: asp.netreactjsasp.net-core

解决方案


您的 fetch 调用中有错字:

更改fetch('values');fetch('api/values');


推荐阅读