1/* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import { Dispatch, Unsubscribe } from '../redux' 17 18export interface MapStateProp<State = any> { 19 (state: State): any; 20} 21 22export interface MapDispatchProp { 23 (dispatch: Dispatch): any; 24} 25 26function merge(obj: any, props: any) { 27 const keysProp = Object.keys(props) 28 console.info(`mapProps: ${JSON.stringify(keysProp)}`) 29 for (let i = 0; i < keysProp.length; i++) { 30 obj[keysProp[i]] = props[keysProp[i]] 31 } 32} 33 34// The above merge function with no return should be replaced with this merge, so the state in the 35// arkUI pages marked by @State has explicit type, which has great advantages in coding and debugging. 36function merge1<T, U>(obj: T, props: U): T & U { 37 for (const key in props) { 38 (obj as any)[key] = props[key]; 39 } 40 return obj as T & U; 41} 42 43export function connect(store, mapToProps: MapStateProp, mapToDispatch: MapDispatchProp): (state: any) => void { 44 return (obj) => { 45 console.info(JSON.stringify(store.getState())) 46 merge(obj, mapToProps(store.getState())) 47 merge(obj, mapToDispatch(store.dispatch)) 48 store.subscribe(() => merge(obj, mapToProps(store.getState()))) 49 } 50}