繁体   English   中英

如何防止Shopify Polaris React应用过早连接到Shopify服务?

[英]How can I prevent a Shopify Polaris React app from connecting to Shopify service too soon?

我是新来的人,我正在尝试使用React和Polaris React套件构建一个基本的Shopify应用程序。

TL:DR;

在从服务器异步获取数据之前,如何防止渲染React组件? 使Polaris应用程序连接到shopify服务的正确方法是什么?

完整说明

问题在于渲染功能应将商店域添加到<AppProvider/>元素上的属性。 IE浏览器。 <AppProvider shopOrigin="https://user-store.myshopify.com"/>但是,域因使用该应用程序的商店而异。

鉴于React是在客户端渲染的,我需要向服务器发送请求以检索当前商店域。 但这是在应用渲染后发生的:

render() {

    return (
      <AppProvider
        shopOrigin={this.state.shop} {/* Null when first rendered  */}
        debug={true}
      > ... </AppProvider>

这样一来,Polaris应用程序便会以商店域的Null值尝试连接到Shopify,并且一切都中断了。

我已经能够通过在第一个渲染器上使render函数返回Null来防止这种情况,但这有点让人讨厌

 render() {   

    if (typeof this.state.shop === 'undefined') {/* true on first render */}
      return null; { /* prevent rendering at this stage */ }

    return (
      <AppProvider
        shopOrigin={this.state.shop}
        debug={true}
      > 

这是我用来从服务器获取域的异步函数

 constructor() {
    super();

    this.state = {};
  }

  componentDidMount() {
    this.callApi()
      .then(res => this.setState(res))
      .catch(err => console.log(err));
  }

  callApi = async () => {
    const response = await fetch('/shopify/config');
    const body = await response.json();

    if (response.status !== 200) throw Error(body.message);

    return body;
  };

一种简单的方法是将'isLoading'属性保持在组件的状态,该属性最初设置为true

组件完成获取所需数据后,调用this.setState({isLoading: false})

然后,组件的render方法应如下所示:

render() {
    const { isLoading } = this.state;

    if (isLoading) {
        return <span>loading...</span>
    }

    return <AppProvider {...props}/>
}

这样,您的应用程序就不会尝试连接到Shopify服务,直到完成数据获取为止。

当然,您可以随意设置render的返回值,也可以在其中放置一个加载图标/动画,或者只返回一个空的<div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM