如何在 react 中从功能组件调用服务类方法



我有一个 OIDC 客户端服务

export class AuthService {
public userManager: UserManager;
private user: any = null;
constructor() {
const settings = this.getClientSettings();
this.userManager = new UserManager(settings);
}
public isLoggedIn(): boolean {
return this.user != null && this.user.access_token && !this.user.expired;
}
loadUser() {
this.userManager.getUser().then((user) => this.user = user);
}
public getUser(): Promise<User | null> {
return this.userManager.getUser().then((user) => this.user = user);
}
public login(): Promise<void> {
return this.userManager.signinRedirect();
}
}

功能组件

export default function NavMenu() {

useSelector((state: ApplicationState) => state.oidcUser);
const dispatch = useDispatch();
const [state, setState] = useState({
menu: {
open: true,
coordinates: undefined
}
});
const onClose = () => {
setState({
...state, menu: {
open: false,
coordinates: undefined
}
})
}
authService: AuthService;
const login = () => {
authService.startAuthentication(window.location.pathname);
};
const menuOptions = [
'Save',
'Edit',
'Cut',
'Copy',
'Paste',
];
return (<div>
<TopAppBar>
<TopAppBarRow>
<TopAppBarSection align='start'>
<TopAppBarTitle>Falcon</TopAppBarTitle>
</TopAppBarSection>
<TopAppBarSection align='end' role='toolbar'>
<div>
{(() => {
if (true) {
return (
<Button raised type="button" onClick={() => { login }}>Portal</Button>
)
} else {
return (
<Menu
open={state.menu.open}
onClose={onClose}
coordinates={state.menu.coordinates}
onSelected={(index, item) => console.log(index, item)}>
<MenuList>
{menuOptions.map((option : any, index : any) => (
<MenuListItem key={index}>
<MenuListItemText primaryText={option} />
{/* You can also use other components from list, which are documented below */}
</MenuListItem>
))}
</MenuList>
</Menu>
)
}
})()}
</div>
</TopAppBarSection>
</TopAppBarRow>
</TopAppBar>
</div>);
}

尝试呼叫

authService: AuthService;
const login = () => {
authService.startAuthentication(window.location.pathname);
};

收到错误找不到名称身份验证服务

如何从反应功能组件调用服务类方法。

在这里,您可以在功能组件中执行以下操作:

import * as React from "react";    
import { AuthService } from "./AuthService";
export default function NavMenu() {
const authService = new AuthService();
const login = () => {
authService.startAuthentication(window.location.pathname);
}
return (
<div className="App">
<h1>Hello NavMenu</h1>
</div>
);
}

如果您还有其他问题,很乐意为您提供帮助!

相关内容

  • 没有找到相关文章

最新更新