• react错误捕获


    import {Component} from 'react';
    export default class WeirwoodErrorBoundary extends Component {
    
        static getDerivedStateFromError(error) {
            return {error};
        }
    
        constructor(props) {
            super(props);
            this.state = {
                error: null
            };
        }
    
        componentDidCatch(error, errorInfo) {
            this.setState({
                error
            });
            if (window.__Weirwood) {
                window.__Weirwood.error.captureException(error);
            }
        }
        render() {
            if (this.state.error) {
                return <div>页面出错了!请稍后重试</div>;
            }
            return this.props.children;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    调用

    Main.js

    import React from 'react';
    import ReactDOM from 'react-dom';
    import {Switch} from 'react-router';
    import {Provider} from 'react-redux';
    import ConnectedRouter from './common/connected-react-router';
    import WeirwoodErrorBoundary from './common/components/WeirwoodErrorBoundary';
    import './resource/style/main.less';
    import InitRoutes from './router';
    ReactDOM.render(
            <WeirwoodErrorBoundary>
                <Provider store={store}>
                    <ConnectedRouter history={history}>
                        <Switch>
                            <InitRoutes store={store} history={history} />
                        </Switch>
                    </ConnectedRouter>
                </Provider>
            </WeirwoodErrorBoundary>,
            document.getElementById('root')
        );
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    src/app/entry/action.js

    /**
     * @file action
     * @author luoyide@baidu.com
     *
     **/
    
    import {get, noop, omit, pick, set, size} from 'lodash';
    import {get as getCookie} from 'lib/storage/cookie';
    import {set as setStorage, get as getStorage, remove as removeStorage} from 'lib/storage/localStorage';
    import {updateRoute, getUrlParam} from 'common/util';
    import {logoutAccount} from 'common/util/logout';
    import {resetShopInfo} from 'app/shopInfo/action';
    import {getBizCode} from 'common/util/platform';
    import {NO_AUTH} from 'src/config';
    import {
        SELECTED_APP_KEY,
        INIT_API_CACHE_KEY,
        STORAGE_LOGIN_TYPE,
        INIT_FOR_DUXIAODIAN,
        FROM_MERCHANT_KEY,
        PARENT_ID_KEY
    } from 'common/config/storageKey';
    import {COOKIE_NAME} from 'common/config/cookieConfig';
    import {appInitIsloadingSelector} from 'common/selectors/platform';
    import message from 'common/containers/wrapReduxFlowForm/formItemFactory/message';
    import ACTIONS from './actionTypes';
    import {HOME_GUIDE_LOCAL_STORAGE_NAME, SHOW_MENU} from './config';
    import {loadCommissionInfo} from './service/loadCommissionInfo';
    import {INIT_SESSION_ID} from 'common/config/logConfig';
    import {isPassSelector} from '../../../src/selectors';
    import {checkUserQulification} from '../assetCenter/service';
    import {errorInformer} from '../assetCenter/util';
    import {whichBizTypeSelector} from '../../common/selectors/bizType';
    import baiduMonitor, {setUserProperty} from '../../common/util/baiduMonitor';
    import {basicInfoAction} from './reducer/basicInfo';
    import {userIdSelector, optIdSelector, isSonAccountSelector} from 'common/selectors/platform.js';
    import {getShopRegisterPath} from 'src/common/util/getPath';
    import {needGetHagList} from 'src/common/config/hagInfo';
    import {initSurvey} from './util';
    import * as api from './service';
    import * as homeApi from 'app/home/apis';
    import {onlineService} from 'src/common/util/quarkRequest';
    
    const INIT_CACHE_TIME = 43200000; // 12小时
    /**
     * 更新路由
     * @param {string} options.nav      一级导航path
     * @param {Object} options.match    match
     * @param {Object} options.isPurifyQuery    路由
     * @return {Function}               回调
     */
    export const onUpdateRoute = (params = {}) => (dispatch, getState) => {
        const {nav, match} = params;
        dispatch({
            type: ACTIONS.MENU_CLICK_ROUTER_CHANGE,
            payload: {
                key: nav,
                match: match
            }
        });
        // 路由点击统一增加参数,功能:单独针对生活服务有子店路由全部拼接subShopId参数,兼容强制刷新选中子店逻辑
        updateRoute(params, dispatch, getState());
    };
    
    export const getToken = state => {
        const isPass = isPassSelector(state);
        const ucToken = getCookie('CPTK__513') || getCookie('__cas__st__513') || '';
        const token = isPass
            ? ''
            : ucToken;
        return token;
    };
    
    export const changeSelectedBizAction = (appInfo = {}) => (dispatch, getState) => {
        const {appId, subAppId, appName} = appInfo;
        const shopId = get(appInfo, 'shopInfo.shopId');
        const fromMerchant = getStorage(FROM_MERCHANT_KEY);
        const monitorShopInfo = {
            appId,
            subAppId,
            appName,
            sessionId: INIT_SESSION_ID,
            fromMerchant: +fromMerchant || 0
        };
        shopId && (monitorShopInfo.shopId = shopId);
        appId && setUserProperty(monitorShopInfo);
        const bizCode = getBizCode(appInfo);
        // 存储选中的业务线到localStorage
        setStorage(SELECTED_APP_KEY, appInfo);
        dispatch({
            type: ACTIONS.SELECTED_BIZ_CHANGE,
            payload: {
                ...appInfo,
                bizCode
            }
        });
        dispatch(resetShopInfo(get(appInfo, 'shoInfo')));
    };
    
    export const initBasicInfo = (params = {}) => (dispatch, getState) => {
        dispatch({
            type: basicInfoAction['ON_BASIC_INFO_RESET']
        });
    };
    
    export const changeBasicInfo = (params = {}) => (dispatch, getState) => {
        dispatch({
            type: basicInfoAction['ON_BASIC_INFO_CHANGE'],
            payload: params
        });
        if (window.__Weirwood && window.__Weirwood.error && window.__Weirwood.error.setContext) {
            window.__Weirwood.error.setContext(params);
        }
        if (window.__Weirwood && window.__Weirwood.perf && window.__Weirwood.perf.addVar) {
            window.__Weirwood.perf.addVar(params);
        }
    };
    
    export const passBindUcAction = (params = {}) => (dispatch, getState) => {
        return dispatch(api.passBindUcService(params));
    };
    
    export const fetchAppListAction = (params = {}) => (dispatch, getState) => {
        return dispatch(api.fetchAppInfoListServer(params));
    };
    
    export const getMenuListAction = (params = {}) => (dispatch, getState) => {
        const bizCode = whichBizTypeSelector(getState());
        return dispatch(api.fetchMenuListServer(params, bizCode));
    };
    
    export const getUserHagInfo = (params = {}) => (dispatch, getState) => {
        return dispatch(api.fetchUserHagInfoServer(params));
    };
    
    export const appInitLoadingChangeAction = (payload = false) => (dispatch, getState) => {
        dispatch({
            type: ACTIONS.APP_INIT_IS_LOADING,
            payload
        });
    };
    
    export const getShopDetailAction = (params = {}) => (dispatch, getState) => {
        return dispatch(api.fetchShopDetailServer(params));
    };
    
    export const getShopContactAction = (params = {}) => (dispatch, getState) => {
        return dispatch(homeApi.getShopContactInfo(params));
    };
    
    export const checkHasRoleAction = (params = {}) => (dispatch, getState) => {
        return dispatch(api.fetchCheckHasRoleServer(params));
    };
    
    export const changeSelectedBiz = (
        app = {},
        openedJumpPath,
        finallyCb = {}
    ) => (dispatch, getState) => {
        const appInitIsloading = appInitIsloadingSelector(getState());
        // 如果正在请求,不执行后续动作;
        if (appInitIsloading) {
            return Promise.resolve();
        }
    
        // 如果URL上存在fromMerchant字段,则代表来源为新登录页merchantLogin,存入redux。后续不置为false
        const urlFromMerchant = getUrlParam('fromMerchant', window.location.search) || 0;
        const urlParentid = getUrlParam('parentid', window.location.search) || 0;
        urlFromMerchant && setStorage(FROM_MERCHANT_KEY, parseInt(urlFromMerchant, 10));
        urlParentid && setStorage(PARENT_ID_KEY, parseInt(urlParentid, 10));
    
        const {
            initFinally,
            menuListFinally
        } = finallyCb;
        dispatch(changeSelectedBizAction(omit(app, ['mainUcId'])));
        const appId = get(app, 'appId');
        const subAppId = get(app, 'subAppId');
        // 当缓存中存在对应mainUcId,这里会传入mainUcId
        const mainUcId = get(app, 'mainUcId');
        const appParams = {
            appId,
            subAppId,
            shopId: null,
            mainUcId
        };
        dispatch(appInitLoadingChangeAction(true));
        const bizCode = whichBizTypeSelector(getState());
        const nowDate = new Date();
        const today = `${nowDate.getFullYear()}-${nowDate.getMonth() + 1}-${nowDate.getDate()}`;
        const cacheParams = {
            duxiaodian: {
                cacheKey: INIT_FOR_DUXIAODIAN,
                cacheType: 'local',
                // 获取对应日期对应用户缓存
                cacheGet: ({cacheLocalItem, paramsStr}) => {
                    return get(cacheLocalItem, `${today}.${paramsStr}`, '');
                },
                // 设定缓存
                cacheSet: ({response, paramsStr}) => {
                    // 仅在入驻完成后缓存
                    if (get(response, 'data.shopInfo.showMenu', 0) !== SHOW_MENU) {
                        return;
                    }
                    // 取出缓存
                    const allInit = getStorage(INIT_FOR_DUXIAODIAN) || {};
                    // 追加本次缓存
                    set(allInit, `${today}.${paramsStr}`, JSON.stringify(response));
                    // 取当天缓存进行缓存set
                    setStorage(INIT_FOR_DUXIAODIAN, pick(allInit, today));
                },
                delay: 1000 * 20
            },
            others: {
                cacheKey: INIT_API_CACHE_KEY.init,
                cacheType: 'local',
                cacheTime: INIT_CACHE_TIME,
                active: 'manual'
            }
        };
        // init接口获取ucId和passId,营销模块ucId必传,店铺保存接口必须passId,
        return dispatch(api.passBindUcService(appParams, cacheParams.others)).then(res => {
            if (res.redirect) {
                return;
            }
            // 存储账户类型
            setStorage(STORAGE_LOGIN_TYPE, getCookie(COOKIE_NAME.LOGIN_TYPE));
            dispatch(changeBasicInfo({
                userId: res.ucId,
                optId: res.sonUcId,
                userName: res.mainUcName,
                optName: res.ucName,
                hasHitSmallFlow: res.localSmallFlow || 0 // 0为未命中,1为命中
            }));
            // 多主账号子账号,跳转shopCenter
            // TODO 这里可能影响mcc需要重点回归 @wuxinru
            if (!mainUcId && res?.isSonAccount && size(res?.mainShopList) > 1) {
                dispatch(appInitLoadingChangeAction(false));
                dispatch(onUpdateRoute({nav: '/shopCenter', isReplace: true}));
                return;
            }
            // 存储账户类型
            const shopId = get(res, 'shopInfo.shopId');
            // 咨询状态改为上线
            if (shopId) {
                onlineService({
                    serviceId: res.ucId,
                    optId: res.sonUcId,
                    shopId
                }).catch(noop);
            }
            const showMenu = get(res, 'shopInfo.showMenu');
            baiduMonitor('all_system_entry');
            dispatch(changeSelectedBizAction({
                ...app,
                shopInfo: get(res, 'shopInfo'),
                isInHag: res.isInHag,
                ...(res?.shopInfo
                    ? {
                        appId: get(res, 'shopInfo.appId'),
                        subAppId: get(res, 'shopInfo.subAppId')
                    }
                    : {}
                )
            }));
            // 拉取当前用户的hag名单
            if (needGetHagList.length) {
                dispatch(api.fetchUserHagInfoServer({
                    item: {
                        hagRoles: needGetHagList,
                        shopId
                    }
                })).catch(noop);
            }
            dispatch(appInitLoadingChangeAction(false));
            const shopRegisterNav = getShopRegisterPath();
            const isSonAccount = isSonAccountSelector(getState());
            // 店铺ID存在并且showMenu为1
            if (shopId && showMenu) {
                // 请求菜单需要加菜单loading态
                dispatch(api.fetchMenuListServer({
                    ...appParams,
                    shopId
                }, isSonAccount ? {} : { // 子账号不缓存菜单
                    cacheKey: INIT_API_CACHE_KEY.moduleList,
                    cacheType: 'local',
                    cacheTime: INIT_CACHE_TIME,
                    delay: 60000
                })).then(() => {
                    // 请求完新业务线的菜单,需要跳转首页
                    if (openedJumpPath) {
                        if (openedJumpPath === shopRegisterNav) {
                            updateRoute({nav: '/home'}, dispatch, getState());
                        }
                        else {
                            updateRoute({nav: openedJumpPath}, dispatch, getState());
                        }
                    }
                }).finally(() => {
                    menuListFinally && menuListFinally();
                }).catch(noop);
                dispatch(api.fetchCheckHasRoleServer({roleName: 'ai_create_product'})).catch(noop);
            }
            // 未入驻成功,进入店铺入驻
            else {
                dispatch(onUpdateRoute({nav: shopRegisterNav, isReplace: true}));
            }
    
            if (!window.surveyApp) {
                initSurvey({
                    userid: res.ucId,
                    optid: res.sonUcId
                });
            }
            dispatch(authority());
        }).catch(err => {
            const errCode = +get(err, 'errors.0.code');
            let defaultMsg = '';
            if (errCode === NO_AUTH) {
                defaultMsg = '抱歉,您当前账号暂无开通业务权限。';
            }
            const errMsg = get(err, 'errors.0.message', defaultMsg);
            errMsg && message.error(errMsg);
        }).finally(re => {
            initFinally && initFinally();
        });
    };
    
    // 鉴权
    export const authority = () => (dispatch, getState) => {
        const userId = userIdSelector(getState());
        const optId = optIdSelector(getState());
        const changeAuth = payload => dispatch({
            type: ACTIONS.ON_AUTH_INFO_CHANGE,
            payload
        });
        changeAuth({userId, optId});
    };
    
    // 发起登出
    export const logoutUcAndPass = () => (dispatch, getState) => {
        // 手动点击退出登录
        logoutAccount();
    };
    
    
    export const getCommissionInfo = params => dispatch => {
        return dispatch(loadCommissionInfo(params));
    };
    
    export const checkQulification = () => dispatch => {
        dispatch(checkUserQulification({})).catch(e => {
            errorInformer(e.error);
        });
    };
    
    export const setGuideStorage = () => dispatch => {
        const {KEY, OPTIONS: {VISIBLE}} = HOME_GUIDE_LOCAL_STORAGE_NAME;
        // 用户登录时不存在localStorage:KEY时,添加KEY
        !getStorage(KEY) && setStorage(KEY, VISIBLE);
    };
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362

    router/index.js

    import {connect} from 'react-redux';
    import {bindActionCreators} from 'redux';
    import * as actionCreators from 'src/app/entry/action';
    import {
        menuMapSelector,
        getShopShowMenuRes,
        getRouterPathname,
        getUrlSearch,
        isShopRegisterPage,
        querySubShopIdSelector
    } from 'common/selectors/platform';
    
    import {
        isServiceEcommerceBizSelector
    } from 'common/selectors/bizType';
    import Main from './Main.js';
    
    const mapStateToProps = state => {
        const menuMap = menuMapSelector(state);
        const isShopRegister = isShopRegisterPage(state);
        const isService = isServiceEcommerceBizSelector(state);
        return {
            menuMap,
            showMenu: getShopShowMenuRes(state),
            pathname: getRouterPathname(state),
            search: getUrlSearch(state),
            isShopRegister,
            isService,
            querySubShopId: querySubShopIdSelector(state)
        };
    };
    
    const mapDispatchToProps = dispatch => {
        return bindActionCreators(actionCreators, dispatch);
    };
    
    export default connect(mapStateToProps, mapDispatchToProps)(Main);
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
  • 相关阅读:
    大数据-玩转数据-Flink CEP编程
    SolidWorks2020详细步骤安装教程
    Spring 10: AspectJ框架 + @Before前置通知
    Typora、Markdown笔记为文字添加颜色的快捷键设置
    React报错之Objects are not valid as a React child
    初始SpringBoot——SpringBoot的概念和使用
    前端经典面试题 | 闭包的作用和原理
    [自制操作系统] 第08回 开启分页机制
    数智随行 | 机器学习与图像技术:库存管理的下一个前沿
    MySQL 使用客户端以及SELECT 方式查看 BLOB 类型字段内容总结
  • 原文地址:https://blog.csdn.net/qq_33332184/article/details/134312511