Gri*_*420 7 asp.net reactjs asp.net-core
不允许在标题中说帮助,但我需要帮助理解这个模板。我第一次尝试使用 ASP.NET Core Web 应用程序 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 });
}
}
Run Code Online (Sandbox Code Playgroud)
除了这一行之外,这一切对我来说都很有意义: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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我假设的类似 WeatherForecast 的模型类
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; }
}
}
Run Code Online (Sandbox Code Playgroud)
这是获取的结果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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
并复制了这样的视图:
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 });
}
}
Run Code Online (Sandbox Code Playgroud)
当我访问该FetchValues页面时,我收到此错误:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 fetch-values:1
Run Code Online (Sandbox Code Playgroud)
并检查检查 -> 网络 -> 预览 -> 值(或获取值),预览为空。
这是我的问题:
1.) 到底在哪里weatherforecast?我如何看待它,以便我可以复制我的价值观所发生的事情?
2.) 为什么预览中的值是空的?相同的代码在 API 项目模板中完美运行。
3.) 这个项目模板有官方文档吗?我找不到超过 1 个无用页面:https://learn.microsoft.com/en-us/aspnet/core/client-side/spa/react ?view=aspnetcore-5.0&tabs=visual-studio
| 归档时间: |
|
| 查看次数: |
1294 次 |
| 最近记录: |