代码之家  ›  专栏  ›  技术社区  ›  andrew

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

  •  0
  • andrew  · 技术社区  · 7 年前

    TL:博士;

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

    问题是render函数应该将存储域添加到 <AppProvider/> 元素。即。 <AppProvider shopOrigin="https://user-store.myshopify.com"/> 但是,域因使用应用程序的商店而异。

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

    这导致北极星应用程序自动连接到Shopify 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;
      };
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Henry Woody    7 年前

    一个简单的方法就是 'isLoading' 组件状态中的属性,初始设置为 true .

    this.setState({isLoading: false}) .

    那么组件的渲染方法应该如下所示:

    render() {
        const { isLoading } = this.state;
    
        if (isLoading) {
            return <span>loading...</span>
        }
    
        return <AppProvider {...props}/>
    }
    

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

    render 不管你喜欢什么,可以在里面放一个加载图标/动画,或者只返回一个空的 <div> .