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

标签 javascript reactjs asynchronous shopify polaris

我是 React 新手,我正在尝试使用 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商店域名的值(value)和一切都崩溃了。

我已经能够通过让渲染函数返回Null来防止这种情况发生。在第一次渲染时,但这感觉有点hacky

 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() {
    const { isLoading } = this.state;

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

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

这样,您的应用在完成数据提取之前不会尝试连接到 Shopify 服务。

当然你可以将返回值设为render无论你喜欢什么,也许可以在其中放置一个加载图标/动画,或者只是返回一个空的 <div> .

关于javascript - 如何防止 Shopify Polaris React 应用过早连接到 Shopify 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51804921/

相关文章:

javascript - Meteor 和 React 的双向数据绑定(bind)

javascript - 如何更改 img 标签中 svg 源的颜色?

javascript - 防止 Scala 不必要地转义 XML 中的双引号

javascript - 使用 Ramda 进行函数组合

javascript - 尝试在 React Native 中将 mp3 文件作为参数传递,但出现错误。我该如何解决这个问题?我使用Expo-av作为引用

linux - 如何实现实用的光纤调度器?

javascript - 连接 : how to handle each subscribe with a specific next function as independent

c# - 延迟异步方法的最小起订量返回不延迟

javascript - Base64编码/解码并下载URL中生成的内容

javascript - jQuery src 选择器问题