基于现有.NET Core MVC项目中的URL有条件地呈现react组件



我有一个现有的.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并显示适当的组件,但我无法使其工作。我只是得到以下错误:

错误:应用程序(…(:渲染未返回任何内容。这通常意味着缺少返回语句。或者,要不呈现任何内容,请返回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;

组件/定价/销售/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/
}
]
}
}

错误非常清楚。你忘了return:

const App = () => {
return ( // <-- you are missing this
<Switch>
<Route exact path="/Pricing/Sales" component={SalesIndex} />
</Switch>
)
}

你也可以写

const App = () =>
<Switch>
<Route exact path="/Pricing/Sales" component={SalesIndex} />
</Switch>

如果你喜欢的话,可以选择parens。

最新更新