React is used as a framework for real development
- UI framework antd. The design
- Routing Management (SPA) React -router-dom
- State management redux, MOBx, DVA
UI framework antd. The design
-
NPM install antd //
-
NPM install react-app-rewired customize-cra // The default configuration is customized
/* package.json */ "scripts": {-"start": "react-scripts start", + "start": "react-app-rewired start", - "build": "react-scripts build", + "build": "react-app-rewired build", - "test": "react-scripts test", + "test": "react-app-rewired test",}Copy the code
-
The project root directory creates a config-overrides. Js to modify the default configuration.
-
NPM install babel-plugin-import // Load antD component styles on demand
-
Replace moment.js with day.js
-
npm install antd-dayjs-webpack-plugin dayjs
-
Complete configuration to use
const { override, fixBabelImports, addLessLoader, addWebpackPlugin, } = require("customize-cra"); const AntdDayjsWebpackPlugin = require("antd-dayjs-webpack-plugin"); module.exports = override( // AntD component libraries are loaded on demand fixBabelImports("import", { libraryName: "antd".libraryDirectory: "es".style: "true",}).// Antd time component replaces moment.js with day.js addWebpackPlugin(new AntdDayjsWebpackPlugin()), // Use less style preprocessing to customize theme styles addLessLoader({ javascriptEnabled: true.modifyVars: { "@primary-color": "#1DA57A"}}));Copy the code
-
-
NPM start Check the result
Single Page Application (SPA)
- Integrated the react – the router – the dom
- npm install react-router-dom
Integrated the react – the router – the dom
-
React-router-dom Common components and apis
- BrowserRouter and HashRouter wrap all routes
- Add /#/ to the HashRouter path
- BrowserRouter is built on the H5 History API to facilitate route jumps
- Switch Distinguishes between BrowserRouter and HashRouter packet route hops
- BrowserRouter and HashRouter wrap all routes
-
Route Displays the interface for mounting different routes
-
Link is used to jump, similar to the A label
-
Code-mode jump
import { useHistory } from "react-router-dom"; history.push("/home"); Copy the code
-
-
Adjusting the directory structure
-
Create the Components directory to hold the components
- Create the ClassComponent/FunctionComponent folder and move it to the Components directory
-
Create pages directories to store different pages
-
Create component, home page components
-
home.jsx
const Home = () = > { return <div>Home</div>; }; export default Home; Copy the code
-
component.jsx
import { Divider } from "antd"; import ClassComponent from ".. /components/ClassComponent"; import FunctionComponent from ".. /components/FunctionComponent"; const Component = () = > { return ( <div> <ClassComponent title="The Class components" /> <Divider /> <FunctionComponent title="Function module" /> </div> ); }; export default Component; Copy the code
-
-
-
Modify app.js to use ANTD component for interface layout
import React from "react"; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; import { Layout, Menu } from "antd"; import Home from "./pages/home"; import Component from "./pages/component"; import "./App.css"; const { Header, Content, Footer } = Layout; const App = () = > { return ( <div classNam="App"> <Router> <Layout className="layout"> <Header> <Menu theme="dark" mode="horizontal" defaultSelectedKeys={["home"]} style={{ lineHeight: "64px}} "> <Menu.Item key="home"> <Link to="/">Home page</Link> </Menu.Item> <Menu.Item key="component"> <Link to="/cc">component</Link> </Menu.Item> </Menu> </Header> <Content style={{ padding: "0 50px}} "> <div style={{ background: "#fff", padding: 24.minHeight: "88vh}} "> <Switch> <Route path="/cc"> <Component /> </Route> <Route path="/"> <Home /> </Route> </Switch> </div> </Content> <Footer style={{ textAlign: "center}} ">Full stack Technology ©2021 Created by Peach Blossom</Footer> </Layout> </Router> </div> ); }; export default App; Copy the code
Running effect
The router parameters
-
Passing parameters
- By defining <Route path=”/path/:id”></Route>
- The Link transmission
<Link to="/path/xxxx">
-
To obtain parameters
- Create HOC with withRouter, and get the pass parameters from props
- Code way
- Create HOC with withRouter, and get the pass parameters from props
import { useParams } from "react-router-dom"; let { id } = useParams(); Copy the code
- Create HOC with withRouter, and get the pass parameters from props
More reference reactrouter.com/web/guides/…
Dva status management
Why use DVA for state management?
- Dva encapsulates Redux, exposing easy-to-use apis (synchronous, asynchronous)
- The latter combines UMi.js + ANTD. design + ANTD. dedign-Pro out of the box mid-platform front-end/design solutions
Dva use
Chestnut: use DVA to build a user interface for user management
Install DVA dependencies
npm install dva
Copy the code
Modify index.js to use DVA to manage state
// import React from "react";
// import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import dva from "dva";
import { createBrowserHistory as createHistory } from "history";
import userModel from "./models/user";
const app = dva({
history: createHistory(),
onError: (err, dispatch) = > {
console.log("onError ===> ", err, dispatch); }}); app.model(userModel); app.router(App); app.start(document.getElementById("root"));
// ReactDOM.render(
//
//
// ,
// document.getElementById("root")
// );
reportWebVitals();
Copy the code
Create user Model and manage user state
-
models/user.js
const userModel = { // Namespace namespace: "user".// Initialize the state data state: { userList: [{id: 1.name: "Peach blossom",}]},effect: { // Asynchronous request. It can be a network request, delayed operation *submit(action, { put, call, select }){},},reducers: { // Add a user add(state, { payload: { user } }) { let { userList = [] } = state; const temp = userList.concat(); temp.push({ id: userList.length + 1. user });return { ...state, userList: temp, }; }, // Delete the user delete(state, { payload: id }) { let { userList = [] } = state; return { ...state, userList: userList.filter((item) = >item.id ! == id), }; }},// Listen for route changes subscriptions: { setup({ dispatch, history }) { // history.listen(location => {});,}}};export default userModel; Copy the code
-
Namespace that enables Dispatch to trigger different types of action (redux) depending on business data
dispatch({ type: "user/add".payload: { /* Data transfer */}})Copy the code
-
Effect triggers asynchronous actions, like redux-saga
-
Reducers Synchronized action
-
Subscriptions can monitor routing changes, obtain parameters, and conduct authentication operations
-
Building the User Interface
-
Create user.jsx in the Pages directory
-
Use ANTD components for UI layout
-
Use CONNECT for data subscription binding
import { connect } from "dva"; import { Form, Input, Button, Table } from "antd"; const User = ({ user, dispatch }) = > { const { userList } = user; const [form] = Form.useForm(); console.log(user); const onFinish = (values) = > { dispatch({ type: "user/add".payload: { user: values, }, }); form.resetFields(); }; const onDelete = (id) = > { dispatch({ type: "user/delete".payload: id, }); }; const columns = [ { title: "ID".dataIndex: "id".key: "id"}, {title: "Name".dataIndex: "name".key: "name"}, {title: "Operation".key: "action".render: (text, record) = > ( <Button size="middle" onClick={()= >OnDelete (record. Id)} > delete</Button>),},];return ( <div> <Form name="user_form" form={form} layout="inline" onFinish={onFinish}> <Form.Item name="name" rules={[{ required: true.message: "Please input your name!" }]} > <Input placeholder="Name" /> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit">add</Button> </Form.Item> </Form> <Table style={{ width: 500.marginTop: 10 }} rowKey={(record)= > record.id} columns={columns} dataSource={userList} /> </div> ); }; export default connect(({ user }) = > ({ user, }))(User); Copy the code
-
The effect