preface
Recently, I learned the React library. I started from scratch and wrote a background management step by step to understand some knowledge points of React in actual projects. The code in this article is relatively brief, you can see the specific project code from the Github address.Copy the code
Project Preview address
At present, mock data is used in the project, and the account can be entered at will. React Manages demo projects in the background
Project Preview screenshot
- The login
2. Registered3. The first page
Dependencies used by the project
- React // Core library
- Antd / / UI library
- Axios // request dependencies
- Echarts // Diagrams in the project
- React-loadable // dynamic loading
- React-router-config // Route configuration
- React-router-dom // Route dependency
- Redux, react-redux, redux-saga // redux series of dependencies
- other
directory
- Install create-React-app scaffolding and create the project
- Refine the directory structure according to personal habits or company standards
- Use react-loadable to load components dynamically
- Configure the AXIOS unified request
- Configure react-redux and redux-sagas
- The code address
Initialize the project
Create-react-app is a react scaffolding tool that can be used to create a project.
// Node >= 8.10 and NPM >= 5.6 NPX create-react-app Project name CD Project name NPM start or YARN startCopy the code
Note that NPX is not a typo — it is the package runtime tool that comes with NPM 5.2+
Improving the directory structure
So this is the one I’m using so far and I’m going to define it this way, the directory structure is what I need.
Project name | | - SRC / / resource file | | | | - assets / / pictures, fonts, and other static resource file | | - components / / common components | | - routes / / routing configuration file | | - store / / State storage | | - style / / public CSS file | | - utils / / public methods | | - page views / / | | - index. The js / / entry file | | - craco. Config. Js / / Because we don't have to NPM run reject will configure exposed, | / / this configuration file is used to create the react - app | / / the default configuration to specify a scheme. | - other filesCopy the code
Project file parsing
Entry file index.js
import React from 'react'; import ReactDOM from 'react-dom'; Import {HashRouter} from 'react-router-dom' import {renderRoutes} from "react-router-config" // a tool library for configuring static routes import { Provider } from 'react-redux' import { ConfigProvider } from 'antd' import zhCN from 'antd/es/locale/zh_CN' Import HTTP from '@/utils/ HTTP '// HTTP request import routes from '@/routes' import '@/style/index.scss' import ConfigureStore from '@/store' import rootSaga from '@/store/sagas' const store = RootSaga configureStore (). The map (saga = > store. RunSaga (saga)) / / HTTP hang under the global, the page can go directly to reference, use: $HTTP [' get '|' post '|... React.$http = http ReactDOM.render( <Provider store={store}> <ConfigProvider locale={zhCN}> <HashRouter> {renderRoutes(routes)} </HashRouter> </ConfigProvider> </Provider>, document.getElementById('root') );Copy the code
The routing file
// Since react-loadable is installed, we can do the same as vUE routing. Write a unified configuration file import React from 'React' import {Redirect} from 'React -router-dom' import RouteComponents from './components' const routes = [ { path: '/login', component: RouteComponents.Login }, { path: '/forget', component: RouteComponents.Forget }, { path: '/404', component: RouteComponents.NotFound }, { render: (props) => { const token = getToken() if (!token) { return <Redirect to="/login" /> } return <RouteComponents.Layout {...props} /> }, routes: [ { path: '/', exact: true, render: () => <Redirect to="/home" /> }, { path: '/home', component: RouteComponents.Home }, { path: '/user', component: RouteComponents.User } ] }, { path: '*', component: Routecomponents. NotFound}] export default routes // ------- components.js file contents ---------------- import React from 'react' import Loadable from 'react-loadable' import Loading from '@/components/ Loading '// encapsulates a Loading component const Layout = Loadable({ loader: () => import('@/views/Layout'), loading: Loading }) ... export default { Layout, ... }Copy the code
Store the file
/ / index, js, Import createSagaMiddleware from 'redux-saga' import {createStore, applyMiddleware } from 'redux' import concatReducer from './reducers' export default function configureStore(initialState) { const sagaMiddleware = createSagaMiddleware() return { ... createStore(concatReducer, initialState, applyMiddleware(sagaMiddleware)), runSaga: sagaMiddleware.run } }Copy the code
Configure axiOS unified requests (cookies, intercepts, unified error reporting, etc.)
Why encapsulate Axios? First of all, we used AXIos as the request method, which performed well in all aspects. Second, in a single page application, there are a lot of requests involved. For common operations such as request interception, response interception, and unified error handling, we can save a lot of code by encapsulating AXIos. My example is relatively simple, with the following code:
import axios from 'axios' import { message } from 'antd' ... Const HTTP = axios.create({baseURL: MOCK_API, // withCredentials: true, timeout: 1000 * 60 * 3 }) http.interceptors.request.use(function(config) { const { url } = config if (! whiteApi.includes(url)) { const token = window.sessionStorage.getItem('token') if (! Token) {return promise. reject({"code": 4002, // "message": "in order to obtain the token, please login first ", "data": null }) } config.headers.Authorization = token } return config }, function(error) { return Promise.reject(error) }) http.interceptors.response.use(function(response) { const data = response.data if (data.code === 200) { return data.data } else { message.error(data.message || data.desc) return Promise.reject(response) } }, function(error) { if (error.code === 4002) { message.error(error.message) window.location.href = '#/login' return Promise.reject(error) } return Promise.reject(error.response) }) export default httpCopy the code
Mock Api
Since the project is just for learning demos, no real backend requests are made, so far all requests are mock data, here are two free online apis that are currently available. At present, there is no specific introduction to the use of these two. If necessary, we will introduce them in the future.
- RAP interface management platform
- Fastmock Online interface Mock platform
Because of corporate network limitations, Rap addresses are not accessible in the company, so the sample project uses FastMock, both of which are very useful.
Contents of the page under views
Because the page is basically a table, the content of the presentation of information, there is nothing very special, here is not too much description, the specific can be viewed in the code
Code address (how useful, remember to give a thumbs up.
Making: github.com/xuRookie/re… This is the code address, feel good, you can start in the upper right corner of the address, thank you.
summary
At this point, there is a basic React background management, because the react proficiency is contacted by myself, there is not much configuration. Almost all of the things used in the project are things that are used in the back office. So, practice writing it down. If you have any questions, please leave them in the comments section.