In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how to use React + Redux + React-router to build scalable front-end applications. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.
How to make good use of various frameworks to improve the quality of front-end development is a problem that everyone is exploring. The editor will introduce how to use React and its related technologies to develop actual front-end projects.
To solidify this practice, a tool called Rekit was also developed to ensure that projects always follow this practice. Now that the tools have been further improved, you can also use Rekit to understand the practical solutions mentioned in this article.
In fact, no matter what technology is used, an ideal Web project probably needs to consider the following aspects:
Easy to develop: in functional development, do not need to pay attention to the complex technical architecture, can intuitively write function-related code.
Easy to expand: when adding new functions, there is no need to adjust the existing architecture, the new features and existing functions have a good isolation, and can be well connected. The addition of new features does not cause significant performance problems.
Easy to maintain: the code is intuitive, easy to read and easy to understand. Even new developers can quickly understand the technical architecture and code logic.
Easy to test: code unit is good, can use pure function as much as possible. There is no or little need for mock to complete the unit test.
Easy to build: the code and static resource structure follow the mainstream pattern and can be built using standard build tools. There is no need to implement complex build logic on your own.
These aspects are not independent of each other, but depend on each other and restrict each other. When one aspect achieves *, other points will be affected. For example, writing a counter function can be done in one page with jQuery, but it is easy to develop, but not easy to expand. Therefore, we usually need to make a tradeoff between these points according to the actual project situation to achieve a suitable project state. Fortunately, with the rapid development of front-end technology, the continuous emergence of new technologies has helped us to achieve great improvement in all aspects.
What this article will introduce is how to use React + Redux + React-router to build scalable front-end applications. Extensibility is emphasized here, because the traditional front-end implementation is often inadequate in the face of complex applications, the code structure is easy to be confused, and the performance problems are difficult to solve. Extensibility means being able to support complex projects from the initial stage of the project. First of all, let's look at the main technologies involved.
React
React believes that you are already very familiar with its idea of componentization and the implementation of virtual DOM is a subversive change, so that the front-end development can continue to improve in new directions. Both React-hot-loader,Redux and React-router are able to provide such powerful functionality because they make full use of these features of React.
Redux
Redux is the JavaScript program state management framework. Although it is a general framework, it works better with React, because when the state changes, React can complete the optimized UI update logic by the virtual DOM mechanism without paying attention to the details of the change.
Redux is also considered to be one of the most difficult technologies to master in the whole React ecosystem. Although its action,reducer and various middleware fully isolate the code logic, which is often called separation of concerns, it also brings inconvenience to the development to a certain extent. This is also mentioned above, which has been improved in terms of easy maintenance, easy extension, and easy testing, so easy development has been affected.
React-router
Even for a simple application, routing is extremely important. Just as traditional Web programs use pages to organize different functional modules, and different URL to distinguish and navigate, single-page applications use Router to achieve the same function, only rendering at the front end rather than on the server side. The "standard" routing scheme for React applications is to use React-router.
Routing functions not only make it easier for users to use (such as maintaining UI after refreshing pages), but also make us think about how to better organize functional units during development, which is an inevitable requirement after functional complexity. So even if the initial requirements are simple, we should introduce React-router to help us organize our functions in a page-based unit.
Other required technologies
As mentioned earlier, developing front-end applications requires a lot of peripheral technology, which further increases the threshold for front-end development, such as:
Use Babel to support ES2016 and JSX syntax
Seamless combination of Redux and React using react-redux
Using Webpack for Project Packaging
Optimize packaging performance using webpack-dll-plugin
Using ESLint for syntax checking
Unit testing with Mocha,Enzyme,Istanbul
Use Less, Scss, or others for CSS precompilation.
These tools improve the capability and efficiency of front-end development, but it is not easy to understand and configure them, and in fact they are not directly related to the functionality that needs to be developed. Using tools to automate these configurations is inevitable, just as now to develop a C++ application, Visual Studio will help you complete all the configurations and build the appropriate project structure, allowing you to focus on functional logic development. Whether we implement it ourselves or make use of third parties, we should create such a tool chain for our own projects.
After a brief introduction to the related technologies, let's take a look at how to build an extensible Web project.
Organize folder structure by function (feature)
Whether it is Flux or Redux, the official examples provided are all organized by technical logic. For example, the following is the folder structure of Redux's Todo sample application:
Although this model is technically clear, it has major drawbacks in practical projects:
It's hard to expand. When the application function increases and the scale becomes larger, there may be dozens or hundreds of files under a components folder, and the relationship between components is extremely unintuitive.
It's hard to develop. When developing a function, you usually need to develop components, action,reducer, and styles at the same time. Distributing them in different folders seriously affects the efficiency of development. Especially when the project is complex, switching between different files will take a lot of time.
Therefore, we use the way to organize folders by function, that is, the function-related code is put into a folder. For example, for a simple forum program, it may include several core functions such as user,topic,comment.
Each function folder contains its own pages, components, styles, action and reducer.
This folder structure distinguishes the code logic in function rather than technology, so that the application has better expansibility. When adding new functions, you only need to add a new folder; the same is true when deleting functions.
Using the concept of Page
As mentioned earlier, routing is an indispensable part of today's front-end applications, so it corresponds to the component level, which is the page component. So in the process of development, we need to clearly define the concept of the page:
A page has its own URL address. The display and hiding of the page is completely controlled by React-router. When creating a page, it usually means adding a new rule to the routing configuration. This is very similar to traditional Web applications.
A page corresponds to the concept of the container component of Redux. First of all, the page is a standard React component, and then it is encapsulated into a container component through react-redux so that it has the ability to interact with Redux.
Pages are not only the basic module unit of navigation, but also the container of UI related to the same function, and this concept in line with the traditional Web development approach helps to make the project structure easier to understand.
One separate file per action
Using Redux to manage state requires the development of action and reducer. In the official example and almost all tutorials, all the action are placed in one file, while all the reducer are placed in a separate file. This approach is easy to understand but not very extensible, and when the project is complex, both action and reducer files become lengthy and difficult to develop and maintain.
So we use the pattern of a separate file for each action: the action for each Redux and the corresponding reducer are placed in the same file. Another reason for using this approach is that we find that every time we create an action, we need to create a reducer almost immediately to deal with it. Putting them in the same file is good for development efficiency and maintenance.
Take the development of a counter component as an example:
In order to click on the "+" sign to add 1, we first need to create an action of type "COUNTER_PLUS_ONE", and then immediately need to create a corresponding Reducer to update the store data. The official example is to add the corresponding logic to actions.js and reducer.js respectively. The way to use each action separate file is to create a file called counterPlusOne.js and add the following code:
Import {COUNTER_PLUS_ONE,} from'. / constants'; export function counterPlusOne () {return {type: COUNTER_PLUS_ONE,};} export function reducer (state, action) {switch (action.type) {case COUNTER_PLUS_ONE: return {... state, count: state.count + 1,}; default: return state;}}
In our experience, most reducer correspond to the corresponding action and rarely need to be used globally across functions. Therefore, it is perfectly reasonable to put them in a single file, which helps to improve the efficiency of development. It is important to note that the reducer defined here is not a standard Redux reducer because it has no initial state (initial state). It is simply called by the root reducer under the function folder. Note that the reducer is permanently named "reducer" so that it can be loaded automatically.
For asynchronous action (usually remote API requests), error messages need to be handled, so there are multiple standard action in this file. For example, to save an article as an example, in the action file saveArticle.js, there are both saveArticle and dismissSaveArticleError action.
How to deal with cross-functional action?
Although not very common, some action can be handled by multiple reducer. For example, for on-site chat, when a new message is received:
If the chat box is open, the new message is displayed directly.
Otherwise, a notification is displayed indicating a new message.
It can be seen that the action type of NEW_MESSAGE needs to be handled by different reducer, so that it can be represented differently in different UI components. To handle this type of action, there is a reducer.js file under each functional folder where you can handle cross-functional action.
Although the reducer of different action is distributed in different files, they work together with the function-related root reducer to operate on the same state, that is, the same store branch. Therefore, feature/reducer.js has the following code structure:
Import initialState from'. / initialState'; import {reducer as counterPlusOne} from'. / counterPlusOne'; import {reducer as counterMinusOne} from'. / counterMinusOne'; import {reducer as resetCounter} from'. / resetCounter'; const reducers = [counterPlusOne, counterMinusOne, resetCounter,]; export default function reducer (state = initialState, action) {let newState; switch (action.type) {/ / Put global reducers here default: newState = state; break } return reducers.reduce ((s, r) = > r (s, action), newState);}
It is responsible for the introduction of different action reducer, when there is an action, traversing all the reducer and combined with the required global reducer to achieve the update of store. All function-related root reducer is finally combined into the global Redux root reducer to ensure that there is only one store in the global.
It is important to note that whenever you create a new action, you need to register in this file. Because the pattern is very fixed, we can use tools to automatically register the corresponding code. Rekit can help you do this: when you create an action, it automatically adds the appropriate code to the reducer.js, reducing the workload and avoiding errors.
Benefits of using single-file action
In this way, you can bring many benefits, such as:
Easy to develop: when creating an action, there is no need to jump in multiple files
Easy to maintain: because each action is in a separate file, each file is very short, and the corresponding functional logic can be located through the file name
Easy to test: each action can be overwritten with a separate test file, which also contains tests for both action and reducer
Easy to tooling: because applications using Redux have a more complex technical structure, we can use tools to automate some logic. Now we can automatically generate code without parsing.
Easy to statically analyze: global action and reducer usually mean dependencies between modules. At this point, we just need to analyze the reducer.js under the function folder to find all these dependencies.
Rule definition of React-router
Generally speaking, we define all routing rules through a configuration file. Similarly, this approach is not extensible, and when the project becomes complex, the rule definition table becomes lengthy and complex. Now that we have organized folders by function, we can also put the routing rules related to the function under the corresponding folder. Therefore, we can use React-router 's JavaScript API to define routing rules instead of the common JSX syntax.
For example, for a simple forum program, the routing definition for the topic function is placed in features/topic/route.js, as follows:
Import {EditPage, ListPage, ViewPage,} from'. / index'; export default {path:', name:', childRoutes: [{path:', component: ListPage, name: 'Topic List', isIndex: true}, {path:' topic/add', component: EditPage, name: 'New Topic'}, {path:' topic/:topicId', component: ViewPage},],}
All feature-related route definitions are automatically loaded by the global root route configuration, so the route loader has the following code pattern:
Import topicRoute from'.. / features/topic/route'; import commentRoute from'.. / features/comment/route'; const routes = [{path:'/ rekit-example', component: App, childRoutes: [topicRoute, commentRoute, {path:'*', name: 'Page not found', component: PageNotFound},],}]
As you can see, this global routing loader is responsible for loading all feature routing rules. Like root reducer, the code pattern here is very fixed, so you can use tools to maintain this file. When you create a page using Rekit, routing rules are automatically added here.
Use tools to assist in development
As can be seen from the above introduction, it is not easy to develop a React program, even a simple function requires a lot of trivial, but very important code to ensure a good architecture, so that the application is easy to expand and maintain, although the surrounding code is not directly related to the functions you need.
For example, for a forum program, you need a list interface to display recently published topics, and in order to make such a page, we usually need to complete the following steps:
Create a React component named TopicList
Define a routing rule for TopicList
Create a style file named TopicList.css and introduce it in the appropriate location
Use react-redux to encapsulate TopicList components as container components so that they can use Redux store
Create four different action types: FETCH_BEGIN, FETCH_PENDING, FETCH_SUCCESS, FETCH_FAILURE, usually defined in constants.js
Create two action:fetchTopicList and dismissFetchTopicListError
Introducing type constants into action files
Create 4 swtich case in reducer to handle different action types
Introducing type constants into reducer files
Create a test file for a component and its code structure
Create a test file for action and its code structure
Create a test file for reducer and its code structure.
day! There are so many trivial things you need to do before you officially start writing the * * lines of forum logic. When such a thing has been manually repeated many times, we feel that there should be tools to automate such things. To do this, a Rekit toolkit has been created to help generate these file structures and code automatically. Unlike other code generators, Rekit is based on a relatively fixed file and code structure, so it can do more things, such as:
It knows where and how to define routing rules
It knows how to generate action type constants
It knows how to generate type constants based on action names
It knows how to create a reducer based on the action type
It knows how to create meaningful test cases.
With the help of well-maintained tools, we can not pay attention to the technical details, but only focus on the functional code, improving the efficiency of development. Not only that, tools can also reduce errors and maintain a high degree of consistency in code structure, naming, configuration, etc., making code easier to understand and maintain.
Rekit provides a set of tools for the React + Redux development practice proposed in this article, which itself is extensible. You can change the code template as needed, or provide your own tools to improve development efficiency by providing convenient tools for your own project features.
This paper mainly introduces how to use React,Redux and React-router to develop extensible Web applications. There are two core ideas, one is to take the function (feature) as the unit component folder structure, and the other is to adopt the mode of separate files for each action. This makes the code more modular, and adding and removing functions will not have much impact on other modules. At the same time, React-router is used to help realize the concept of page, so that single-page application (SPA) also has the URL navigation function of traditional Web application, which further reduces the coupling lines between functional modules and makes the application structure more clear and intuitive.
In order to support this practice, the article also introduces the Rekit toolset, which can not only help create and configure the initial project template, but also provide a large number of practical tools to help automatically generate the technical structure in the way mentioned in the article, which improves the development efficiency.
On how to use React + Redux + React-router to build scalable front-end applications to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.