javascript - Mobx 加载包装器 React
问题描述
问题
- 编写一个通用组件的最佳方式是什么
假设我们正在调用 API 来获取产品列表,
当 apiStatus 正在获取时,我们将渲染 loadingview
当apiStatus为success时,我们会渲染successView即商品列表
当 apiStatus 由于服务器错误或网络故障而失败时,我们将使用重试按钮呈现失败视图
建议的解决方案1:
// LoadingWrapperWithFailure.js
@observer
class LoadingWrapperWithFailure extends React.Component {
render() {
const { apiStatus, apiError, children, onRetry } = this.props;
switch (apiStatus) {
case API_FETCHING:
// Loading state
return <LoadingView loaderProps={loaderProps} />;
case API_SUCCESS:
// Success state
return children;
case API_FAILED:
// Failed state
return <FailureView onRetry={onRetry} apiError={apiError} />;
default:
return null;
}
}
}
// Usage
@observer
class ProductList extends React.Component {
render() {
const {
apiStatus,
apiError,
productList,
onRetryApi
} = this.props.productStore;
return (
<LoadingWrapperWithFailure
apiStatus={apiStatus}
apiError={apiError}
onRetry={onRetryApi}
>
<SuccessView>
{/* Renders productList when apicall is success */}
</SuccessView>
</LoadingWrapperWithFailure>
);
}
}
> Note: apiStatus, apiError, productList are mobx observable variables
建议的解决方案 2:
// LoadingWrapperWithFailure.js
@observer
class LoadingWrapperWithFailure extends React.Component {
render() {
const { apiStatus, apiError, renderSuccessUI: RenderSuccessUI, onRetry } = this.props;
switch (apiStatus) {
case API_FETCHING:
// Loading state
return <LoadingView loaderProps={loaderProps} />;
case API_SUCCESS:
// Success state
return <RenderSuccessUI />;
case API_FAILED:
// Failed state
return <FailureView onRetry={onRetry} apiError={apiError} />;
default:
return null;
}
}
}
// Usage
@observer
class ProductList extends React.Component {
renderSuccessUI = observer(() => {
const { productList } = this.props.productStore
return (
<SuccessView>
{/* Renders productList when apicall is success */}
</SuccessView>
)
})
render() {
const {
apiStatus,
apiError,
onRetryApi
} = this.props.productStore;
return (
<LoadingWrapperWithFailure
apiStatus={apiStatus}
apiError={apiError}
onRetry={onRetryApi}
renderSuccessUI={this.renderSuccessUI}
/>
);
}
}
最好的方法是什么?
为什么这是最好的方法?
还有其他更好的方法来实现上述功能吗?
如果您需要更多信息,请发表评论。TIA。
解决方案
推荐阅读
- c# - 如何在 ASP.NET MVC 5 中实现 CheckBoxFor?
- sql - 查看 Google Analytics 时如何 UNNEST 和展平 BigQuery 中的所有记录
- php - Show a text depending on the value of a column MySQL
- javascript - Convert repeating "if" to "loop" instead (javascript)
- discord - Discord.js Discord Bot:SyntaxError:输入意外结束
- docker - 运行 Kafka 如何 docker image
- c# - 在单声道上运行的 C# 中处理图形的问题
- javascript - Dynamically delete object property JavaScript
- join - 需要在表单提交后插入一行,基于另一个表的列(JOIN)
- c - My Unknown Numbers of Input Code Duplicates the Last Input