UNPKG

combination-react-app

Version:
150 lines (137 loc) 3.96 kB
import React from 'react'; import connect, { Provider } from 'react-redux'; import { bindActionCreators } from 'redux'; import { DVA, REACTS, } from './constant'; function mapStateToProps(props) { return { ...props, }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators( {}, dispatch, ), }; } function connectProps(mapProps, mapDispatchProps) { return Component => connect(mapProps, mapDispatchProps)(Component); } /** * * @param {*} store * @param {*} app * @param {*} router is not used. */ function getProvider(store, Component, router) {//eslint-disable-line return extraProps => ( <Provider store={store}> { connectProps(mapStateToProps, mapDispatchToProps)(Component) } <Component {...extraProps} /> </Provider> ); } function renderComponent(props, actions) { return component => connectProps(props, actions)(component); } export default function createProcessRoot(props, actions) { return options => { const { appProject, Component: Com, frameworkType } = options; let provider = null; if (Com) { return connect(props, actions)(Com); } return f => { const { separate, dispatch, sync, childRef, reRender, } = f; /** * Prevent multiple rendering */ if (provider) { return provider; } function select(state) { return state; } let currentValue; let previousValue; function handleChange(store) { return () => { currentValue = select(store.getState()); if (previousValue !== currentValue) { if (sync && typeof sync === 'function') { sync(store.getState()); } else { dispatch({ type: 'example/save', payload: { test: currentValue } }); } console.log('Some deep nested property changed from', previousValue, 'to', currentValue); } }; } /** * separate is use to control the child project has separate store or not. */ if (separate) { if (appProject) { /** * for dva react project. */ if (frameworkType === DVA) { const app = appProject(); if (app.toString() === '[object Promise]' && typeof app.then === 'function') { app.then( data => { // setTimeout(() => { const { _store: store, provider: element } = data; previousValue = store.getState(); childRef && childRef({ store }); store.subscribe(handleChange(store)); provider = element; return reRender(); }, err => { console.log(err); }, ).catch(erro => { console.log(erro); }); provider = (<div style={{ display: 'none', color: 'red' }} />); return provider; } const { _store: store, provider: element } = app; setTimeout(() => { previousValue = store.getState(); childRef && childRef({ store }); store.subscribe(handleChange(store)); }, 0); // unsubscribe(); provider = element; return provider; } else if (frameworkType === REACTS) { /** * for origin react project. */ const { RootElement, store } = appProject; setTimeout(() => { previousValue = store.getState(); childRef({ store }); store.subscribe(handleChange(store)); }, 0); return RootElement; } } /** * for origin react component. */ } return null; // 暂时不处理 }; }; }