首页 > 解决方案 > 将高阶组件与连接到 Redux 存储的现有类组件一起使用

问题描述

所以我对 React 很陌生,我正在做一个使用 Redux 的项目。任务是获取 Okta 上下文以访问身份验证令牌。

问题是我有这个来自 Okta 的例子

import fetch from 'isomorphic-fetch';
import React, { Component } from 'react';
import { withOktaAuth } from '@okta/okta-react';

export default withOktaAuth(class MessageList extends Component {
  constructor(props) {
    super(props)
    this.state = {
      messages: null
    }
  }

  async componentDidMount() {
    try {
      const response = await fetch('http://localhost:{serverPort}/api/messages', {
        headers: {
          Authorization: 'Bearer ' + this.props.authState.accessToken
        }
      });
      const data = await response.json();
      this.setState({ messages: data.messages });
    } catch (err) {
      // handle error as needed
    }
  }

  render() {
    if (!this.state.messages) return <div>Loading...</div>;
    const items = this.state.messages.map(message =>
      <li key={message}>{message}</li>
    );
    return <ul>{items}</ul>;
  }
});

...他们在其中使用和导出 withOktaAuth 高阶组件。我无法使用现有代码执行此操作,因为它是作为类组件编写的:

class FetchData extends React.PureComponent<InspectionBrowserProps> {
  // This method is called when the component is first added to the document

    public componentDidMount() {
    this.ensureDataFetched();
    }

  // This method is called when the route parameters change
    public componentDidUpdate() {
  }

    public render() {
     --- render stuff--
  }
}
}

然后通过连接导出到 redux 存储

export default connect(
    (state: ApplicationState) => state.inspectionBrowser, // Selects which state properties are merged into the component's props
    InspectionBrowserStore.actionCreators // Selects which action creators are merged into the component's props
)(FetchData as any);

那么如何使用 withOktaAuth 组件获取访问令牌,但仍然将现有组件作为类连接到 Redux 存储?感觉就像苹果和橘子对我来说有点问题。

标签: reactjstypescriptreduxokta

解决方案


推荐阅读