我是 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/