UNPKG

sunmao-sdk

Version:

榫卯-开箱即用赋能-sdk

139 lines (128 loc) 3.66 kB
import React, { useState, useEffect, useRef } from "react"; import CpDetail from "./CpDetail"; import CpTable from "./CpTable"; import CpComposite from "./CpComposite"; import { CP } from ".."; import { fetchPageDetails } from "./../net/service"; import * as commonUtils from "./../utils/commonUtils"; import * as localStorageUtils from "./../utils/localStorageUtils"; import CpTabs from "./CpTabs"; const displayName = "CpBase"; const CpBase = props => { const { schema, faultSchema, defaultSchemaMap = {}, flag, api, ...otherProps } = props; // 用户自定义配置key前缀 const customKey = `${CP.getSunmaoParams().user}-${flag}-`; // 根据类型添加后缀 const [configSchema, setConfigSchema] = useState(null); useEffect(() => { // 优先精准静态缓存 if ((!schema || !setSchema(schema.trim())) && flag) { // 缓存提高体验 const json = CP.schemaConfigMap[flag]; // 优先数据缓存 单页面静态缓存 批量静态缓存 setSchema(json || faultSchema || defaultSchemaMap[flag]); // 正常请求 fetchPageDetails({ key: flag }).then(res => { setTimeout(() => { // 延迟渲染 避免并行 setSchema((res.content || res.preContent).trim()); }, 300); }); } }, [flag, schema]); const setSchema = content => { try { setConfigSchema(JSON.parse(content)); CP.schemaConfigMap[flag] = content; localStorageUtils.setObject("sunmao_schemaConfigMap", CP.schemaConfigMap); } catch (e) { commonUtils.log(e, displayName); return false; } return true; }; // 拦截刷新 const onSdkInterceptRefresh = () => {}; // 页面刷新 const onSdkPageRefresh = () => { window.location.reload(); }; // 通用apis const apis = { onSdkPageRefresh, noRefresh: onSdkInterceptRefresh, ...api }; const getLayout = () => { try { const { pageType } = configSchema; switch (pageType) { case "sunmao_detail": return ( <CpDetail customKey={customKey} schema={configSchema} api={apis} {...otherProps} /> ); case "sunmao_composite": return ( <CpComposite // customKey={customKey} schema={configSchema} api={apis} defaultSchemaMap={defaultSchemaMap} {...otherProps} /> ); case "sunmao_tabs": return ( <CpTabs // customKey={customKey} schema={configSchema} api={apis} defaultSchemaMap={defaultSchemaMap} {...otherProps} /> ); default: return ( <CpTable customKey={customKey} schema={configSchema} api={apis} {...otherProps} /> ); } } catch {} return <div>页面出错</div>; }; return configSchema ? ( <div> {CP.getSunmaoParams().env === "pre" && commonUtils.getUrlQuery().sunmaoEnv === "pre" ? ( <a target="_blank" href={`https://fl-btrip-cp.pre-fc.alibaba-inc.com/page?sunmaoProjectId=${ CP.getSunmaoParams().projectId }&appId=${CP.getSunmaoParams().appId}&key=${flag}`} rel="noopener noreferrer" > 榫卯配置 </a> ) : null} {getLayout()} </div> ) : ( <div>页面构建中...</div> ); }; export default React.memo(CpBase);