【问题标题】:Create a React HOC that provides context data from server创建一个从服务器提供上下文数据的 React HOC
【发布时间】:2018-07-09 23:25:04
【问题描述】:

我想创建一个类似于 react-router 的 HOC,它为组件提供一些与上下文相关的数据。上下文数据需要从服务器获取。

  import React, { Component } from "react";

export function withSearchContext(ComponentToWrap) {
  return class extends Component {

    //should actually come from server
    state = {
      searchContext: {
        key: "adedd34ddDdd1"
      }
    };

    componentDidMount() {
      this.getContextFromServer();
    }

    getContextFromServer() {
      this.props.getContextFromServer().then(response => {
        this.setState({searchContext: response.data});
      });
    }

    render() {
      return (
        <ComponentToWrap {...this.props} searchContext={this.state.searchContext} />
      );
    }
  };
}

我正在使用它

import React, { Component } from 'react';
import { withSearchContext } from '../../Context';

@withSearchContext
class AccountDetail extends Component<{}, {}> {
  componentDidMount = () => {
    console.log(this.props.searchContext);
  };

   render() {
     if(this.props.searchContext.key){
      return (
        <div className="detail-view flex-container">
          {this.props.searchContext.key}
        </div>
     } 
     return <div> Loading ... </div>;
    );
   }
}

问题是我包装它的每个组件都会调用 HOC。因此,对服务器的调用会发生多次。但是,我只需要 HOC 运行一次并向使用 HOC 的任何组件提供上下文。如何在 React 中实现这一点?

【问题讨论】:

  • 我看到你的标签中有 redux。你在用 redux 吗?
  • @gretro 是的,我也在使用 Redux。

标签: reactjs redux higher-order-functions higher-order-components


【解决方案1】:

如果您使用Redux,最好将响应对象存储在存储中并通过连接的组件访问它。其余的答案是如何完成,但不建议这样做。在context 方法中,您需要确保在呈现应用程序之前完成req/res,这意味着在收到响应后调用ReactDOM.render

您可以通过使用 React context&lt;SearchContextProvider /&gt; 组件来实现这一点。然后使用 HOC 返回知道上下文的组件。包装您的应用程序后实例化提供程序并将响应对象作为道具传递。以下是高级解决方案。

SearchContextProvider.js

class SearchContextProvider extends React.Component {
  static childContextTypes = {
    search: PropTypes.object
  };

  getChildContext() {
    return { search: this.props.search };
  }

  render() {
    return this.props.children; // React16
  }
}

App.js

<SearchContextProvider search={data}>
  <App />
</SearchContextProvider>

withSearchContext.js

export function withSearchContext(ComponentToWrap) {
  return class extends React.Component {
    static contextTypes = {
      search: PropTypes.object
    };

    render() {
      return (
        <ComponentToWrap 
          {...this.props} 
          search={this.context.search} 
        />
      );
    }
  };
}

【讨论】:

  • 谢谢。我正在使用 Redux。那么你的意思是最好在一些更高级别的组件(也许是 App 组件)中分派一个动作创建者来获取初始上下文,然后作为单一事实来源存储在 Redux 中?多个组件可以在其 mapStateToProps 中访问 Search Reducer 状态吗?我的意思是我希望让组件从它们各自的 reducer 访问,这些 reducer 通常与容器组件相关联。
  • 您需要为您的商店考虑合适的形状。例如,如果在整个应用程序中使用了一些初始数据,例如 AppSettings,那么许多组件可以在 mapStateToProps 中映射到它们。
猜你喜欢
  • 1970-01-01
  • 2020-05-12
  • 1970-01-01
  • 2011-08-09
  • 2017-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-15
相关资源
最近更新 更多