preface

This is the first time to write an article. I hope I can communicate with you and learn from you. Although I am still very vegetables, but thirty years in the east, thirty years in the west, mo bullying the poor. Heh heh a little bit of middle two, back to business. This is my first React front-end project. Here are some problems encountered in the development of this project and some small highlights in my opinion.

The project structure

├ ─ server/ / the back end├ ─ Data/ / data├ ─ public// Server static resourcesThe index, js ├ ─ SRC ├ ─ API// Network request code, utility class functions, and related configurations├ ─ assets// Iconfront icon and image├ ─ baseUI// Base UI wheel├ ─ common// Common component library├ ─ components// The page UI component├ ─ pages// Each home page├ ─ routes// Route configuration file└ ─ store// Redux files
      App.jsx               / / the root component
      main.jsx              // Import file
Copy the code

The preparatory work

To create the React project, use the commands to create the project scaffolding

npm init @vitejs/app appName --template react
Copy the code

Use Fiddler to grab the relevant images you need

Use iconfront to get the bottom navigation ICONS

Project start

After the project scaffolding is created, some configuration work is required before the page components can be developed to facilitate the development of later pages. To solve the adaptation problem on different devices, use NPM to install postCSS-Pxtorem plug-in to automatically install PX into REM and lib-fiexible to obtain the size of the root font of the current device, so as to obtain the 1REM size of different devices to complete the adaptation between different devices.

Use React – Router V6 to complete the configuration of the project route, using the latest useRoutes to render the route as a component

export default function WrapRoute() {
    // Render the route using useRoutes
    const routes = useRoutes([
        {path: '/'.exact: true.element: <Navigate to='/home' />},
        {path: '/home'.element: <TabBottom />,
            children: [
                {path: '/home'.exact: true.element: <Navigate to='/home/main' />},
                {path: '/home/main'.element: <Main />},
                {path: '/home/classify'.element: <Classify />},
                {path: '/home/location'.element: <Location />},
                {path: '/home/shopping'.element: <Shopping />},
                {path: '/home/my'.element: <My />}]}, {path: '/detail/:id'.element: <Detail />}])return routes
}
Copy the code

Also note that in React-Router V6, parent and child routes are nested directly, but a
placeholder is required in the parent routing component

Then it is to use the React-Redux repository basic configuration and use combineReducers to merge multiple branch repositories into the master store

import { combineReducers } from 'redux';
import { reducer as mainReducer } from '.. /pages/main/store/index'
import { reducer as shoppingReducer } from '.. /pages/shopping/store/index'

export default combineReducers({
    main: mainReducer,
    shopping: shoppingReducer
});
Copy the code

Complete the design of the bottom navigation bar, set the bottom navigation bar components as a level 1 route, other pages and components are placed in the level 2 route, so that the bottom navigation bar can be displayed on every main page

Here’s a little detail that hits the bottom navigation bar, click highlight and default is a blue background using -webkit-tap-highlight-color: transparent; Make it transparent

Page component development

Home page effect picture

The home page consists of several components

Memo was used for performance optimization for each component. Because it is a mobile project, Bscroll is used for the overall layout. The top search bar searchInput component uses the Bscroll onScroll monitor to trigger the corresponding event to complete the corresponding animation pull down. Using flex: 1; Fixed the right side of the search box and added Transition to complete the animation.

RotationChart component, using Swiper7 to complete the effect development. First contact with Swiper, see the official documentation step by step to understand and complete the component development. It is worth mentioning here that the original default pager effect is a small dot, the official does not provide a horizontal pager effect, and then in order to change the effect I want, I use Chrome to select the small dot, check the default class name, and match! Important modifies some of the original default styles to achieve the desired effect.

MenuBar menuBar component, simple page development, and then to achieve around the top effect is also used Bscroll, then understand only up and down the top effect, this is also referred to a lot of information, finally down the top effect of the source code, found around the top source. It was cool to touch source code for the first time.

Then there is the miHome component, which uses the swiper component, as well as the small text title boxed in the image above, to switch from page to page. The commodity card in the miHome component of the theme also uses Bscroll as a whole, but the default left and right top drawing is cancelled by passing parameters, so that the top drawing can be realized differently from the menuBar component above.

The next two simple components are the Recommend component and the scondaryMenu component, which simply cut the page, and then the scondaryMenu component uses Bscroll to slide, eliminating all the top drawing effect.

The commodity component of the commodity page follows. The first two commodities write two JSON data in the back end, and then the secondaryContent component. The data of the commodities are simulated by mockJS and obtained through AXIOS request. As the data were all json data written by myself, I simply wrote two commodity data, and then jumped to the routing page through route parameter transmission. Different commodity data were obtained through different parameters, and different data pages were displayed in the detail component. Data-driven pages, adhering to the MVVM idea. Here is the code for the MockJS backend that simulates the fake data required by the secondaryContent component. Other page request data is also used in Axios. The backend also uses KOA2-CORS for cross-domain implementation, and KOA-static for using server static resources.

router.get('/home/context'.async (ctx) => {
  let {limit = 20, page = 0 } = ctx.request.query
  // console.log(limit,page);

  let data = Mock.mock({
   'list|20': [{
    'id': '@increment'."imgUrl1": Random.image('150x150'),
    "imgUrl2": Random.image('150x150'),
    "imgUrl3": Random.image('150x150'),
    "price|1-10000": 10000.'name': '@ ctitle (5, 10)'."text1": "(1) @ ctitle (5, 10)"."text2": "(2) @ ctitle (5, 10)"."text3": "(3) @ ctitle (5, 10)".'imgsrc': Random.image('150x150'),
    "isSelect": false."count": 1}]})// Return the response body
  ctx.body = {
    success: true.data: data
  }
})
Copy the code

Use Axios to request the mockJS simulated back-end data, 20 pieces at a time, and with lazy loading, a loading graph is displayed before the data arrives for some performance optimization. Then set a listening event to load more using the handlePullUp in Bscroll and use the React-hooks function useEffect() to slide to the bottom of the page.

Baidu Map API

This is my first time to contact baidu Map API, also encountered some problems, but grasp the nettle felt good. The core part of the entire page is the use of Baidu map API. The rest is simple page development.

Use the official React-BMapgl documentation. Install the React component library using NPM and load it through the ES module

npm install react-bmapgl --save
Copy the code

The difficulty was in customizing the icon style of the tag. I first used the provided
component to set the map overlay and then found that it did not provide a function for click events. It then switches to using the provided
points for annotation. However, I have been confused about how to customize the Maker icon for a long time. I have searched a lot of articles on the Internet but failed to find how to customize the Maker icon in the React function component. In the end, it is still based on the experience of looking at Bscroll source code mentioned earlier, as indicated in the source code screenshot above. IconString defines the default Icon style, then I try using bmapgl.icon as follows

// Customize the icon
let icon1 = new BMapGL.Icon(xiaomi, new BMapGL.Size(20.20))
Copy the code

The first parameter accepted is the address of the picture, here I use the local picture definition variable named Xiaomi introduced from outside, the second parameter is to set the size of the picture, etc. Other parameters can also be accepted.

Then you can click on the different Maker ICONS to select the different address cards below, using the Maker attribute click event. Select the corresponding address card with the same index. Then mark the Bscroll node with useRef first to obtain the address card automatically sliding to the selected address card using the scrollTo method in Bscroll.

Shopping cart function

The following is the core part of the project, React-Redux data flow management.

In the react components, sometimes encounter data or state of a component to be used in another component, then we can use the context, the data can be Shared among multiple components or state, so that would have multiple components can access or modify the data or status, if the component can also be used in the father and son when the props to share state, But only between parent and child components. Therefore, both of them have certain disadvantages. Therefore, react-Rudex can be used for unified data flow management. Cannect is used to connect the corresponding warehouse if data or status is needed, and the data in the warehouse can only be changed by notifyingreducer function to modify the state or data through Diapatch, which greatly ensures the data security in the warehouse and better data management.

Create a branch store under the Shopping page component and initialize an array of selectGoods. First check if the array is empty and display the different page components. Connect the warehouse with connect. The first parameter mapStateToPorps is connected to a certain data in the specified warehouse. The second parameter mapStateToDispatch defines the dispatch function and informs the Reducer function to perform corresponding operations, such as adding and deleting data in the store. Data flow management for the Redux warehouse. Click “Add” on the home page to add the trigger event of buying a car, add the data of the current page to the selectGoods array, and then use map to cycle the data of the selectGoods array to display the corresponding commodity card on the page, so as to drive the MVVM idea of the interface. Other selected, deleted, full selection of Redux data management is no longer described, you can see the source link at the end of the article to view the source code.

conclusion

The react project is also a summary of my 21 years of front-end learning. Then I want to continue to learn front-end knowledge, continue to learn and improve myself, and HOPE to share knowledge and exchange learning with more people. Finally, if this article is helpful to you, I hope you can like it a lot!! 🙇

The source code

Project source: Gitee address

Preview address online, PC view using chrome phone to simulate iPhone 12Pro best, still in the update iteration