如何从React中的功能组件调用服务类方法

时间:2020-07-03 11:39:36

标签: reactjs react-hooks react-component react-functional-component redux-react-hook

我有一个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 个答案:

答案 0 :(得分: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>
  );
}

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