【发布时间】:2019-08-15 19:03:12
【问题描述】:
我正在尝试学习如何使用 ASP.NET Core 创建 React 应用程序。很有帮助的是,他们提供了 React 项目模板,其中一些示例使我能够了解一切是如何协同工作的。但是,为了确保我完全理解,我想添加我自己的代码。我从“Hello World”开始 v. small - 我只想在主页上显示它。
这是我的 home.js 文件:
import React, { Component } from 'react';
export class Home extends Component {
static displayName = Home.name;
constructor(props) {
super(props);
this.state = { message: "" };
fetch('Home/Index')
.then(res => res.json())
.then((result) => {
this.setState({ message: result.message });
});
}
render () {
return (
<div>
<h1>Message:{this.state.message}</h1>
</div>
);
}
}
这是我希望在主页上呈现的后端代码: HomeController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace TestingReactDotNet.Controllers
{
public class HomeController : Controller
{
// GET: /<controller>/
public string Index()
{
return "Hello World";
}
}
}
我的问题是 - 我在 Home.js 中 return() 将代码合并到 HomeController.cs 并显示 "hello world" 是什么?
抱歉,如果这个问题似乎已在其他地方得到解答 - 我使用的是 Mac,因此文件结构和 Visual Studio IDE 完全不同,我很难理解已经存在的许多教程/答案。
【问题讨论】:
-
您需要从您的 react 应用程序对 .net 核心应用程序的 Index 方法进行 ajax 调用,并以这种方式检索字符串“Hello World”。一旦你得到响应,就需要在反应端添加一个变量,并让它在渲染器的返回语句中渲染。
-
非常感谢@Chris - 我试图对 .net 核心应用程序的 Index 方法进行 ajax 调用(我已经编辑了我的原始帖子以显示我的尝试!)这不起作用(它什么都不显示)所以我一定是哪里出错了?