React background management front end system (based on open source framework development) start

Fizz in nuggets 38275 2021-02-23 03:43:50
react background management end based


Blogging is not easy , If it helps you, please like it . If you have time, you can comment on it .         The background of this system is like this , A friend wants to see some of the existing systems , User data , News data , Just see , There is no need to add, delete or modify functions in the short term , Let me build a simple background system for him to see . It's too easy for someone with four years of development experience , Let's get started , The easiest way is to use open source projects directly github.com/PanJiaChen/… download , Get rid of unwanted routes , Create several new table routes , Just copy the page and use it .

      So let's do that , The whole system will not take more than half a day to build , And this open source framework I've played very well , It's easy to develop later . however , The plan was rejected by me . Why that ? Because I want to get out of the comfort zone . Take on a bigger challenge , At present and vue Go hand in hand React The project is also very process , A lot of companies are using it . So , Technology stack is to use React 了 . But build from scratch , It's not worth the time , Because you need to integrate a lot of things , Infrastructure takes a long time . Hence, GitHub Last meal ,Ok Found two more reliable projects to use , One is  ant-design-pro  The other is antd-admin  The two projects are similar , Technology stack used react,ant-design,dva,Mock   be based on Antd UI Design language   Although I am dva and ant-design Understanding is not deep , But I'm still ready to challenge . If you don't enter the tiger's den, you will get the tiger's son .

  In the beginning, I chose antd-admin  Because the code is standard ,UI It's more in line with my aesthetic . Let's do it

  First, find a list page , Read the code carefully , Figure out the dependency , Then create a new directory , Copy all the files on the list page , Distribution route , Set the permissions .

But when calling the interface , Although the interface is called , But the page didn't refresh , No matter how to debug it , I'm in a hurry . Finally, I had to ask my colleagues for help , But they're also rarely used React. It was just like this for a day , I decided to put the question aside first , The answer must be in the code , Take a break , Don't be limited by this problem , The result is that we can't see the nature of the problem . In the absence of a solution to this problem , I started another project  ant-design-pro Attempts to . Because I know , That page doesn't display data , I'm sure I'll solve it , It's just a matter of time , When I solved , I must have thought I was too stupid , It turns out that's true .

  Pause for a while on the issue of data not being displayed , I began to explore ant-design-pro

  Let me talk about it here , Confusion and problems when a rookie takes over a new project .

  First of all, when the project starts, we will see the page URL,URL It corresponds to our page one by one , It means that we are based on URL You can accurately find the corresponding page in the project , Or page entry . Of course, the page might have a main page , Multiple subpages . I forget to say a little bit here ,URL Corresponding page The configuration of this correspondence , It's called routing .

notice URL, You can find the route , You can find the page , Finding the page completes the first step of getting familiar with the project , Here we are , You can write your own static page , You can see it in the browser with your own route . Is it simple . This is the general idea . But some frameworks have the authority to intercept , The new page route may need to give the login permission to appear .  I'll give a demonstration with specific page cases later .

The first step has been learned , The next step is to enter the page , Look at how the data on the page flows , event , How parameters are configured . This one is more difficult , Is also familiar with the front-end project's core knowledge . Key points , a key , a key Usually a page , There will be initialization functions , For example, a vue The component will be on mounted Interface to get data by calling state , To render a page .React Will be in componentDidMount Life cycle call the interface to get data . Every page or component can be two or more components , It's a combination of , And the parameters of the component are also intricate , The performance of components , Events are controlled by these parameters . In addition to simply understanding these parameters , You also need to understand how these components come together .

I said enough Now I'll use a list page to show you How do I understand a front-end project and development

I take ant-design-pro The query form page of is an example

We have it /list/table-list This route goes to the project to search   Open this file  

Obviously this file is routing management   It's clearly written here  /list/table-list Route to file ../routes/List/TableList

Where the

dynamicWrapper(app, ['rule'], ()
 Copy code 

We don't need to understand what he means for the time being , Because our first step is to find the corresponding page according to the route . Instead of understanding every line of code .

open ../routes/List/TableList We see

It's really the page we're looking for , Change one or two words Refresh the page , Sure enough, it has changed . So happy . That's the end of the first step .

It must be mentioned that global search is a very good skill , We must learn to . in addition When searching for routing , Some routes are written separately , Like routing /list/table-list Yes, there is /list and /table-list Direct search /list/table-list Can't find it , This is the time to try a single search , Cross comparison , perhaps , Look for a directory like routing This is a simple and practical method . Go to this step , You can create a page by yourself , With a route to see .

Next, let's talk about how to quickly understand the general structure of the page after entering the page

import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
Row,
Col,
Card,
Form,
Input,
Select,
Icon,
Button,
Dropdown,
Menu,
InputNumber,
DatePicker,
Modal,
message,
Badge,
Divider,
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './TableList.less';
const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
Object.keys(obj)
.map(key => obj[key])
.join(',');
const statusMap = ['default', 'processing', 'success', 'error'];
const status = [' close ', ' Running ', ' Online ', ' abnormal '];
const CreateForm = Form.create()(props => {
const { modalVisible, form, handleAdd, handleModalVisible } = props;
const okHandle = () => {
form.validateFields((err, fieldsValue) => {
if (err) return;
form.resetFields();
handleAdd(fieldsValue);
});
};
return (
<Modal
title=" New rules "
visible={modalVisible}
onOk={okHandle}
onCancel={() => handleModalVisible()}
>
<FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label=" describe ">
{form.getFieldDecorator('desc', {
rules: [{ required: true, message: 'Please input some description...' }],
})(<Input placeholder=" Please enter " />)}
</FormItem>
</Modal>
);
});
@connect(({ rule, loading }) => ({
rule,
loading: loading.models.rule,
}))
@Form.create()
export default class TableList extends PureComponent {
state = {
modalVisible: false,
expandForm: false,
selectedRows: [],
formValues: {},
};
componentDidMount() {
const { dispatch } = this.props;
dispatch({
type: 'rule/fetch',
});
}
handleStandardTableChange = (pagination, filtersArg, sorter) => {
const { dispatch } = this.props;
const { formValues } = this.state;
const filters = Object.keys(filtersArg).reduce((obj, key) => {
const newObj = { ...obj };
newObj[key] = getValue(filtersArg[key]);
return newObj;
}, {});
const params = {
currentPage: pagination.current,
pageSize: pagination.pageSize,
...formValues,
...filters,
};
if (sorter.field) {
params.sorter = `${sorter.field}_${sorter.order}`;
}
dispatch({
type: 'rule/fetch',
payload: params,
});
};
handleFormReset = () => {
const { form, dispatch } = this.props;
form.resetFields();
this.setState({
formValues: {},
});
dispatch({
type: 'rule/fetch',
payload: {},
});
};
toggleForm = () => {
const { expandForm } = this.state;
this.setState({
expandForm: !expandForm,
});
};
handleMenuClick = e => {
const { dispatch } = this.props;
const { selectedRows } = this.state;
if (!selectedRows) return;
switch (e.key) {
case 'remove':
dispatch({
type: 'rule/remove',
payload: {
no: selectedRows.map(row => row.no).join(','),
},
callback: () => {
this.setState({
selectedRows: [],
});
},
});
break;
default:
break;
}
};
handleSelectRows = rows => {
this.setState({
selectedRows: rows,
});
};
handleSearch = e => {
e.preventDefault();
const { dispatch, form } = this.props;
form.validateFields((err, fieldsValue) => {
if (err) return;
const values = {
...fieldsValue,
updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
};
this.setState({
formValues: values,
});
dispatch({
type: 'rule/fetch',
payload: values,
});
});
};
handleModalVisible = flag => {
this.setState({
modalVisible: !!flag,
});
};
handleAdd = fields => {
const { dispatch } = this.props;
dispatch({
type: 'rule/add',
payload: {
description: fields.desc,
},
});
message.success(' Add success ');
this.setState({
modalVisible: false,
});
};
renderSimpleForm() {
const { form } = this.props;
const { getFieldDecorator } = form;
return (
<Form onSubmit={this.handleSearch} layout="inline">
<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
<Col md={8} sm={24}>
<FormItem label=" Rule number ">
{getFieldDecorator('no')(<Input placeholder=" Please enter " />)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label=" Using a state ">
{getFieldDecorator('status')(
<Select placeholder=" Please select " style={{ width: '100%' }}>
<Option value="0"> close </Option>
<Option value="1"> Running </Option>
</Select>
)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<span className={styles.submitButtons}>
<Button type="primary" htmlType="submit">
Inquire about
</Button>
<Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
Reset
</Button>
<a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
an <Icon type="down" />
</a>
</span>
</Col>
</Row>
</Form>
);
}
renderAdvancedForm() {
const { form } = this.props;
const { getFieldDecorator } = form;
return (
<Form onSubmit={this.handleSearch} layout="inline">
<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
<Col md={8} sm={24}>
<FormItem label=" Rule number ">
{getFieldDecorator('no')(<Input placeholder=" Please enter " />)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label=" Using a state ">
{getFieldDecorator('status')(
<Select placeholder=" Please select " style={{ width: '100%' }}>
<Option value="0"> close </Option>
<Option value="1"> Running </Option>
</Select>
)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label=" Call the number ">
{getFieldDecorator('number')(<InputNumber style={{ width: '100%' }} />)}
</FormItem>
</Col>
</Row>
<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
<Col md={8} sm={24}>
<FormItem label=" Updated date ">
{getFieldDecorator('date')(
<DatePicker style={{ width: '100%' }} placeholder=" Please enter the update date " />
)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label=" Using a state ">
{getFieldDecorator('status3')(
<Select placeholder=" Please select " style={{ width: '100%' }}>
<Option value="0"> close </Option>
<Option value="1"> Running </Option>
</Select>
)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label=" Using a state ">
{getFieldDecorator('status4')(
<Select placeholder=" Please select " style={{ width: '100%' }}>
<Option value="0"> close </Option>
<Option value="1"> Running </Option>
</Select>
)}
</FormItem>
</Col>
</Row>
<div style={{ overflow: 'hidden' }}>
<div style={{ float: 'right', marginBottom: 24 }}>
<Button type="primary" htmlType="submit">
Inquire about
</Button>
<Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
Reset
</Button>
<a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
Retract <Icon type="up" />
</a>
</div>
</div>
</Form>
);
}
renderForm() {
const { expandForm } = this.state;
return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
}
render() {
const {
rule: { data },
loading,
} = this.props;
const { selectedRows, modalVisible } = this.state;
const columns = [
{
title: ' Rule number ',
dataIndex: 'no',
},
{
title: ' describe ',
dataIndex: 'description',
},
{
title: ' Number of service calls ',
dataIndex: 'callNo',
sorter: true,
align: 'right',
render: val => `${val} ten thousand `,
// mark to display a total number
needTotal: true,
},
{
title: ' state ',
dataIndex: 'status',
filters: [
{
text: status[0],
value: 0,
},
{
text: status[1],
value: 1,
},
{
text: status[2],
value: 2,
},
{
text: status[3],
value: 3,
},
],
onFilter: (value, record) => record.status.toString() === value,
render(val) {
return <Badge status={statusMap[val]} text={status[val]} />;
},
},
{
title: ' Update time ',
dataIndex: 'updatedAt',
sorter: true,
render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
},
{
title: ' operation ',
render: () => (
<Fragment>
<a href=""> To configure </a>
<Divider type="vertical" />
<a href=""> Subscribe to alerts </a>
</Fragment>
),
},
];
const menu = (
<Menu onClick={this.handleMenuClick} selectedKeys={[]}>
<Menu.Item key="remove"> Delete </Menu.Item>
<Menu.Item key="approval"> Batch approval </Menu.Item>
</Menu>
);
const parentMethods = {
handleAdd: this.handleAdd,
handleModalVisible: this.handleModalVisible,
};
return (
<PageHeaderLayout title=" Query form ">
<Card bordered={false}>
<div className={styles.tableList}>
<div className={styles.tableListForm}>{this.renderForm()}</div>
<div className={styles.tableListOperator}>
<Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
newly build
</Button>
{selectedRows.length > 0 && (
<span>
<Button> The batch operation </Button>
<Dropdown overlay={menu}>
<Button>
More operations <Icon type="down" />
</Button>
</Dropdown>
</span>
)}
</div>
<StandardTable
selectedRows={selectedRows}
loading={loading}
data={data}
columns={columns}
onSelectRow={this.handleSelectRows}
onChange={this.handleStandardTableChange}
/>
</div>
</Card>
<CreateForm {...parentMethods} modalVisible={modalVisible} />
</PageHeaderLayout>
);
}
}
 Copy code 

Take this page as an example

The first time we read the code, we must read it from top to bottom , remember For the first time . The first time, the first time

First, this file introduces several components React dva moment antd  .....

We need to have a general impression of this library or component , For example, we need to modify the page antd Of Dropdown Components , I'm going antd Let's see what parameters can be adjusted .

Other components and toolkits are like this . If you put the top of the page import I have a general understanding of , Just keep looking down .

Page has const Defines a method , Or a series of objects , This object can be used as a parameter of a component Some of them are small components

  But we need to pay special attention when we see this code

componentDidMount() {
const { dispatch } = this.props;
dispatch({
type: 'rule/fetch',
});
}
 Copy code 

stay React Component's componentDidMount In the life cycle Yes

dispatch({
type: 'rule/fetch',
});
 Copy code 

You don't know dva Maybe you don't understand this code at all , But you can imagine what he meant . What's the role . Or you can just delete the code , See what's changed on the page . The easiest and clearest way to understand the effect of code is Delete directly , See what's wrong , Or something ...O(∩_∩)O ha-ha ~ It's not a good way , But it's easy to use . Come here You probably know This code is about to call the interface to get the data and render it to the page . This kind of writing may be different from what we usually write

We usually call the interface like this

copyrightTypeList().then(res => {
if (res.data.code === 0) {
this.caseTypeList = res.data.data
}
})
 Copy code 

Don't be confused , Accept change . Learn new knowledge , Get out of your comfort zone .

dispatch({ type: 'rule/fetch', }); The key word of this code is rule/fetch First, search the page carefully about rule and fetch Related code .

After a long time in sosu, I finally got better rule It's there ...... This is the end of the article The rest is easy to understand

Property another way to open a project is to open its package.json Put the bag inside Check it one by one , Understand what each package does , usage . It's also a good way to get started quickly

Thank you for reading . If you think it will help you, please remember to like or collect . Feel free to leave a comment . thank you .

版权声明
本文为[Fizz in nuggets 38275]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210222134322244g.html

  1. Configure the certificate to enable ngnix to publish the trusted website of HTTPS
  2. Javascript数据类型
  3. HTTP interface debugging tool! 48000 star HTTP command line client!
  4. Parameter encryption of front end URL link band
  5. HTTP interface debugging tool! 48000 star HTTP command line client!
  6. Three front end frameworks: data binding and data flow
  7. Reading Axios source code (1) -- exploring the realization of basic ability
  8. Event bubble and capture in JavaScript
  9. 【微前端】微前端最終章-qiankun指南以及微前端整體探索
  10. R & D solution e-Car front end monitoring system
  11. [JS] 877 - 35 wonderful knowledge of JavaScript, long experience!
  12. R & D solution e-Car front end monitoring system
  13. High performance nginx HTTPS tuning - how to speed up HTTPS by 30%
  14. 解决ajax跨域问题【5种解决方案】
  15. Top ten classic sorting of JavaScript
  16. HTTP 1. X learning notes: an authoritative guide to Web Performance
  17. Vue3 component (IX) Vue + element plus + JSON = dynamic rendering form control component
  18. My http / 1.1 is so slow!
  19. Why Vue uses asynchronous rendering
  20. The response status was 0. Check out the W3C XMLHttpRequest Level 2 spec for
  21. The tapable instance object hook of webpack4. X core tool library
  22. The tapable instance object hook of webpack4. X core tool library
  23. Using libcurl for HTTP communication in C + +
  24. Using libcurl for HTTP communication in C + +
  25. Using CSS variable in Vue
  26. Deeply understand the update of state and props in react
  27. No matter how fast the Internet is, it's useless! In addition to Baidu disk, there is this website slow to let you eat shriveled
  28. Baidu share does not support the solution of HTTPS
  29. [micro front end] the final chapter of micro front end - Qiankun guide and overall exploration of micro front end
  30. [micro front end] the final chapter of micro front end - Qiankun guide and overall exploration of micro front end
  31. Vue cli creates vue3 project
  32. Nginx reverse proxy for windows authentication using NTLM
  33. Rust tutorial: introduction to rust for JavaScript developers
  34. Deploying personal blog to Tencent cloud with serverless framework
  35. R & D solution e-Car front end monitoring system
  36. JavaScript advanced learning
  37. Spend 1 minute to master these 5 ppt tips, courseware making less detours
  38. Vue: vuex persistent state
  39. React native gets the current network state of the device Netinfo
  40. High performance nginx HTTPS tuning - how to speed up HTTPS by 30%
  41. JavaScript advanced: Javascript object-oriented, JavaScript built-in object, JavaScript BOM, JavaScript encapsulation
  42. JavaScript advanced: Javascript object-oriented, JavaScript built-in object, JavaScript BOM, JavaScript encapsulation
  43. Vue determines whether the El form in the elementui is updated or changed. If it changes, it will prompt whether to save it. If it does not change, it will leave directly
  44. Algorithm problem: sum of two numbers -- JavaScript and Java implementation
  45. High performance nginx HTTPS tuning
  46. JQuery advanced
  47. day 30 jQuery
  48. JQuery:JQuery Basic syntax, jQuery selector, jQuery DOM, comprehensive case check box, comprehensive case random picture
  49. TCP/IP 开胃菜 之 HTTP
  50. JQuery:JQuery Basic syntax, jQuery selector, jQuery DOM, comprehensive case check box, comprehensive case random picture
  51. JavaScript data type
  52. [micro front end] the final chapter of micro front end - Qiankun guide and overall exploration of micro front end
  53. Solve Ajax cross domain problem [5 solutions]
  54. HTTP of TCP / IP appetizer
  55. Optimization of pod creation efficiency in serverless scenario
  56. Iqiyi Sports: experience the ultimate expansion and contraction of serverless, and increase the utilization rate of resources by 40%
  57. First knowledge of HTTP / 1.1
  58. First knowledge of HTTP / 1.1
  59. Webpack learning notes series 05 devserver
  60. Webpack learning notes series 04 - resource processing optimization