Как вызвать метод класса обслуживания из функционального компонента в 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);
    };

Получение ошибки Не могу найти имя authService

Как вызвать метод класса обслуживания из функционального компонента React.

1 ответ

Решение

Здесь вы можете сделать что-то подобное в своем функциональном компоненте:

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>
  );
}

Если возникнут еще вопросы, будем рады помочь!

Другие вопросы по тегам