【发布时间】:2019-11-16 19:25:33
【问题描述】:
我有一个现有的 .NET Core MVC 项目,它目前正在使用 jQuery 和 Knockout.js 来实现它的交互功能。我想从这个转向更现代的方法。我已经看到 .NET Core 有新的 ReactJS 项目模板,但我无法从头开始,所以我尝试将 ReactJS 添加到我的 MVC 项目中的特定页面,随着时间的推移,我将删除所有遗留的 jQuery 和 Knockout 代码.
我已经设法在运行npm run build 时设置和构建 react、webpack 和 babel,并且我可以在页面上显示一个简单的组件。但是,我想根据我所在的页面有条件地渲染一个 React 组件。目前我在 URL /Pricing/Sales 下有一个现有的 MVC 页面/视图,我想用一个 React 组件替换这个视图,同时保持我的网站布局来自 _layout.cshtml(页眉、页脚等)。
我希望能够将我的目标 <div> 放在现有视图中并使用 react-router 检测当前 URL 并显示适当的组件,但我无法让它工作。我只是收到以下错误:
错误:App(...):渲染没有返回任何内容。这通常意味着缺少 return 语句。或者,不渲染任何内容,返回 null。
这是我的代码:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('reactRoot')
);
App.js
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import SalesIndex from './components/pricing/sales/SalesIndex';
const App = () => {
<Switch>
<Route exact path="/Pricing/Sales" component={SalesIndex} />
</Switch>
}
export default App;
components/pricing/sales/SalesIndex.js
import React from 'react';
const SalesIndex = () => <div>Hello from SalesIndex!</div>
export default SalesIndex;
MVC 视图
@model IEnumerable<Sale>
@{
ViewData["Title"] = "Sales";
}
<div class="container">
<div class="page-pricing page-pricing-sales">
<h2>Sales</h2>
<hr />
<div id="reactRoot"></div>
</div>
</div>
MVC 配置
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider services)
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
if (env.IsProduction())
{
//app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Webpack 配置
const path = require('path');
module.exports = {
mode: 'development',
entry: {
index: './Scripts/src/index.js'
},
output: {
path: path.resolve(__dirname, 'wwwroot/dist'),
filename: '[name].js'
},
module: {
rules: [
{
use: {
loader: 'babel-loader'
},
test: /\.js$/,
exclude: /node_modules/
}
]
}
}
【问题讨论】:
标签: c# asp.net-mvc reactjs asp.net-core react-router