如何将 React Hooks 与 ReactJS.NET 一起使用?



我们目前正在将前端从jQuery迁移到 Reactjs.NET。我们正在使用 React 16.8,它允许我们使用 React Hooks 而不是类。

我们成功地设置了我们的项目,并首先尝试了类和服务器端渲染,效果很好,但我的团队更喜欢使用 React Hooks。我尝试使用 Webpack + Babel 来转译 .jsx 文件,因为它不再使用剃须刀辅助程序@Html.React(),但我仍然从我的组件中得到同样的错误。

我们正在使用 Asp.NET 4.x 和 NET Framework 4.7。

这是我的观点 孩子.cshtml

@Html.React("ChildrenForm", new {
familyTiesId = Model.FamilyTiesId 
},
serverOnly:true
)

这是我的 ReactConfig.cs:

namespace Nop.Web
{
public static class ReactConfig
{
public static void Configure()
{
// If you want to use server-side rendering of React components, 
// add all the necessary JavaScript files here. This includes 
// your components as well as all of their dependencies.
// See http://reactjs.net/ for more information. Example:
ReactSiteConfiguration.Configuration
.AddScript("~/Scripts/Components/Customer/ChildrenForm.jsx");
JsEngineSwitcher.Current.DefaultEngineName = V8JsEngine.EngineName;
JsEngineSwitcher.Current.EngineFactories.AddV8();
}
}
}

我的组件:

import React, { useState, useEffect } from 'react';
const ChildrenForm = (props) => {
const [ familyTiesId, setFamilyTiesId ] = useState(props.familyTiesId);
...
}

它应该有效,但相反,我得到:

SyntaxError: Unexpected identifier
Line 20:         @Html.React("ChildrenForm", new {
Line 21:             ddtl = Model.DDTL,
Line 22:             listFamilies = Model.ListFamilies,
...
[JsCompilationException: SyntaxError: Unexpected identifier
at ChildrenForm.jsx:6:8 -> import React, { useState, useEffect } from 'react';]
JavaScriptEngineSwitcher.V8.V8JsEngine.InnerExecute(String code, String documentName) +258
React.ReactEnvironment.EnsureUserScriptsLoaded() +548

似乎我们在使用剃须刀助手 @Html.React 和服务器端渲染时无法导入文件。

如何在服务器端渲染时进行导入并使用 React Hook?

您不必导入它,只需使用:

const [ familyTiesId, setFamilyTiesId ] = React.useState(props.familyTiesId);

只需直接调用useState,无需导入。

最新更新