Home >Web Front-end >JS Tutorial >Dynamic import of React and Redux (with code)
The content this article brings to you is about the dynamic import of React and Redux (with code). It has certain reference value. Friends in need can refer to it. , hope it helps you.
Code separation and dynamic import
For large web applications, code organization is very important. It helps create high-performance and easy-to-understand code. One of the simplest strategies is code separation. Using tools like Webpack, you can split your code into smaller parts, which are divided into two different strategies, static and dynamic.
With static code separation, each different part of the application is first treated as a given entry point. This allows Webpack to split each entry point into a separate bundle at build time. This is perfect if we know which parts of our app will be viewed the most.
Dynamic import uses Webpack's import method to load code. Since the import method returns a promise, you can use async wait to handle the return result.
// getComponent.js async function getComponent() { const {default: module} = await import('../some-other-file') const element = document.createElement('p') element.innerHTML = module.render() return element }
Although this is a very unnatural example, you can see how simple this method is. By using Webpack to do the heavy lifting, we can split the application into different modules. The code we need is only loaded when the user clicks on a specific part of the application.
If we combine this approach with the control structures that React provides us, we can do code splitting through lazy loading. This allows us to delay the loading of code until the last minute, thus reducing the initial page load.
Handling lazy loading with React
In order to import our module, we need to decide what API we should use. Considering we're using React to render content, let's start there.
The following is a simple API that uses the view namespace to export module components.
// my-module.js import * as React from 'react' export default { view: () => <p>My Modules View</p> }
Now that we use the import method to load this file, we can easily access the view component of the module, such as
async function getComponent() { const {default} = await import('./my-module') return React.createElement(default.view) })
However, we still have not used the method in React to lazy load the module . Do this by creating a LazyLoadModule component. This component will be responsible for parsing and rendering the view component for a given module.
// lazyModule.js import * as React from "react"; export class LazyLoadModule extends React.Component { constructor(props) { super(props); this.state = { module: null }; } // after the initial render, wait for module to load async componentDidMount() { const { resolve } = this.props; const { default: module } = await resolve(); this.setState({ module }); } render() { const { module } = this.state; if (!module) return <p>Loading module...</p>; if (module.view) return React.createElement(module.view); } }
The following is a view of using the LazyLoadModule component to load a module:
// my-app.js import {LazyLoadModule} from './LazyLoadModule' const MyApp = () => ( <p className='App'> <h1>Hello</h1> <LazyLoadModule resolve={() => import('./modules/my-module')} /> </p> ) ReactDOM.render(<MyApp />, document.getElementById('root'))
The following is an online example, which adds some exception handling.
https://codesandbox.io/embed/...
By using React to handle the loading of each module, we can lazy load components at any time in the application, including Nested modules.
Using Redux
So far, we have demonstrated how to dynamically load an application's modules. However, we still need to enter the correct data into our module at load time.
Let's see how to connect the redux store to the module. We've created an API for each module by exposing each module's view component. We can extend this by exposing each module's reducer. We also need to expose a name under which our module state will exist in the application's store.
// my-module.js import * as React from 'react' import {connect} from 'react-redux' const mapStateToProps = (state) => ({ foo: state['my-module'].foo, }) const view = connect(mapStateToProps)(({foo}) => <p>{foo}</p>) const fooReducer = (state = 'Some Stuff') => { return state } const reducers = { 'foo': fooReducer, } export default { name: 'my-module', view, reducers, }
The above example demonstrates how our module obtains the state it needs to render.
But we need to do more work on our store first. We need to be able to register the module's reducer when the module is loaded. So when our module dispatche
takes an action
, our store
is updated. We can use the replaceReducer method to achieve this.
First, we need to add two additional methods, registerDynamicModule and unregisterDynamicModule to our store.
// store.js import * as redux form 'redux' const { createStore, combineReducers } = redux // export our createStore function export default reducerMap => { const injectAsyncReducers = (store, name, reducers) => { // add our new reducers under the name we provide store.asyncReducers[name] = combineReducers(reducers); // replace all of the reducers in the store, including our new ones store.replaceReducer( combineReducers({ ...reducerMap, ...store.asyncReducers }) ); }; // create the initial store using the initial reducers that passed in const store = createStore(combineReducers(reducerMap)); // create a namespace that will later be filled with new reducers store.asyncReducers = {}; // add the method that will allow us to add new reducers under a given namespace store.registerDynamicModule = ({ name, reducers }) => { console.info(`Registering module reducers for ${name}`); injectAsyncReducers(store, name, reducers); }; // add a method to unhook our reducers. This stops our reducer state from updating any more. store.unRegisterDynamicModule = name => { console.info(`Unregistering module reducers for ${name}`); const noopReducer = (state = {}) => state; injectAsyncReducers(store, name, noopReducer); }; // return our augmented store object return store; }
As you can see, the code itself is very simple. We're adding two new methods to our store
. Each of these methods then completely replaces the reducer in our store.
Here's how to create an extension store
:
import createStore from './store' const rootReducer = { foo: fooReducer } const store = createStore(rootReducer) const App = () => ( <Provider store={store}> ... </Provider> )
Next, we need to update the LazyLoadModule so that it can be used in our store Register the reducer module in ##.
We can get store
through props
. This is simple, but it means we have to retrieve our store
every time, which can lead to bugs. With this in mind, let the LazyLoadModule component get the store for us.
When the react-redux
// lazyModule.js export class LazyLoadModule extends React.component { ... async componentDidMount() { ... const {store} = this.context } } LazyLoadModule.contextTypes = { store: PropTypes.object, }
现在可以从 LazyLoadModule 的任何实例访问我们的 store。 剩下的唯一部分就是把 reducer 注册到 store 中。 记住,我们是这样导出每个模块:
// my-module.js export default { name: 'my-module', view, reducers, }
更新 LazyLoadModule 的 componentDidMount和 componentWillUnmount 方法来注册和注销每个模块:
// lazyModule.js export class LazyLoadModule extends React.component { ... async componentDidMount() { ... const { resolve } = this.props; const { default: module } = await resolve(); const { name, reducers } = module; const { store } = this.context; if (name && store && reducers) store.registerDynamicModule({ name, reducers }); this.setState({ module }); } ... componentWillUnmount() { const { module } = this.state; const { store } = this.context; const { name } = module; if (store && name) store.unRegisterDynamicModule(name); } }
线上示例如下:
https://codesandbox.io/s/znx1...
总结:
通过使用 Webpack 的动态导入,我们可以将代码分离添加到我们的应用程序中。这意味着我们的应用程序的每个部分都可以注册自己的 components 和 reducers,这些 components 和 reducers将按需加载。此外,我们还减少了包的大小和加载时间,这意味着每个模块都可以看作是一个单独的应用程序。
本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的JavaScript视频教程栏目!
The above is the detailed content of Dynamic import of React and Redux (with code). For more information, please follow other related articles on the PHP Chinese website!