Front-end engineers how to continue to keep warm (a)

For one thing, often repeated, then it is easy to get bored, to feel bored, I lost the original enthusiasm.

Endless business needs, day after day, I felt tedious work, all manual labor;
c end to do more, feel no challenge business logic, boring, demanding design, particularly annoying;
b-side to do more I felt every day to write platform, every day against tasteless data, no chance to play with cool special effects;
technical building to do more, and looked at what they do are tired;
at some fancy stuff, and no job content What is the significance;
want about the latest technology, but the project for historical reasons and often inaccessible ......

Naturally, I lost the original enthusiasm, can not find a sense of accomplishment, and even suspect that he is not not suitable for front-end, is not it a career change, is not to change jobs?
Avoid doing the same thing the same way
if you have been in the same attitude to do the same thing, it is easy to feel bored, no sense of accomplishment. So it is necessary to enhance the efficiency of doing the same thing, back faster and faster to complete, have seen their progress every day, naturally there will be a warm
streamline the code, improve code quality

When you want to copy, you may want to look at where the package, where logic to pull away, where you want to reuse code

Do not let a presence of almost all the same code duplication
we get started, you may have written this code:
<a> Home </a>
<a> About Us </a>
<a> cooperation </a>
<a> join we </a>
copy the code later found, vue can be v-for, react can map, native inserted fragment which can be recycled and finally a one-time append.
Quite obvious that we can find, if less obvious but also reuse of how I found it? Again, when you copy the code you can reuse. For antd Form One common scenario:
<Form1>
<Item label = "name">
{getFieldDecorator ( 'name', {
the rules: [{
required: to true,
Message: "Please enter the name '
}],
}) (<the input />)}
</ Item>
<Item label = "description">
{getFieldDecorator ( 'desc', {
the rules: [{
required: to true,
Message: "Please enter a description '
}]
}) (< INPUT />)}
<



required: to true,
Message: 'Please select the type',
}],
}) (<Checkbox />)}
</ Item>
</ Form1>
copy the code routines are the same, the structure is the same, then we maintain a configuration object to maintain this form:
const items = [
{
label: 'name',
Key: 'name',
Decorator: {
the rules: [{
required: to true,
Message: 'Please enter the name',
}],
},
Component: < INPUT />
},
// ...
]
duplicated code another example of a very long if, back in the front-end processing error code, common piece of code:
// before
IF (type ===. 1) {
the console.log ( 'the Add')
} the else IF (type === 2) {
the console.log ( 'Delete')
} the else IF (=== type. 3) {
the console.log ( 'Edit')
} the else {
Console.log('get')
}

After //
const = {the MAP
. 1: 'the Add',
2: 'Delete',
. 3: 'Edit',
. 4: 'GET',
}
the console.log (the MAP [type])
Copy the code
by arranging the object, rendering cycle to reduce duplication of code

We should have a "lazy write code" mentality
such redux type of Action
const = FETCH_LIST 'FETCH_LIST'
const = FETCH_LIST_SUCCESS 'FETCH_LIST_SUCCESS'
const = FETCH_LIST_FAILED 'FETCH_LIST_FAILED'
const = FETCH_USERINFO 'FETCH_USERINFO'
const = FETCH_USERINFO_SUCCESS 'FETCH_USERINFO_SUCCESS'
const = FETCH_USERINFO_ERROR 'FETCH_USERINFO_ERROR '
copy the code looks very neat and very comfortable with the code, but they all have in common, asynchronous request, the request, the request is successful, the request failed type. Every time new, we first came here three lines of copy, and then change to change. Since almost all, we can write a type generators:
function actionGenerator (k = '') {
const Key = k.toUpperCase ()
return {
... (k
? {

    [`FETCH_${key}_SUCCESS`]: `FETCH_${key}_SUCCESS`,
    [`FETCH_${key}_ERROR`]: `FETCH_${key}_ERROR`,
  }
  : {}),

};
}
// Since then, greatly reducing the number of lines of code action_type
duplicated code Another example of a function for which an object is repeated assignment:
// before
obj.a. 1 =
obj.b = 2
obj.c =. 5
// After
const = {NEWVALS is
a:. 1,
B: 2,
C:. 5
}
// if the traffic is dependent on the original obj inside references, can not change the original object
Object.keys (NEWVALS is) .forEach (Key => {
obj [Key] = NEWVALS is [Key]
})
// if the business inside the obj does not rely on the original reference, you can change the original object
obj obj = {..., ... newVals}
// later want to change anything, I just go and change a line newVals can
copy another example is the code page copy, we can carry out alone to a unified configuration file which, after easily modified
<header> less than two and a half trainee </ header> exercise
<section> I'm just a trainee </ Section>
< ul>
<li> sing </ li>
<li> jump </ li>
<li> RAP </ li>
</ ul>
<footer> Contact: 000 </ footer>
Copy the code CONSTANT = {const
title: 'practice less than two years and a half of trainees',
desc: 'I'm just a trainee'
hobbies: [ 'sing', 'jump', 'RAP'],
tel: '000'
}

<header> CONSTANT.title {} </ header>
<sectionTop> CONSTANT.desc {} </ sectionTop>
<UL>
{
CONSTANT.hobbies.map ((Hobby, I) => <Key Li = {I}> { } Hobby </ Li>)
}
</ UL>
<footer> Contact: {CONSTANT.tel} </ footer>
copy the code looks like this is a write additional code becomes complicated. In general, this is not required. For operational needs, this program can be changed at any time to deal with that change is necessary to change the copy is easy, and does not need to care about page structure, you do not have to copy html inside to find where a file directly write such things put CONSTANT of. But this object also can be reused, there will be the kind of "change of change copy dozens of pages" of the situation.
Another scenario, we usually many such codes may be written:
function the sayHi (name, Word) {
the console.log ( ${name}: ${word})
}
const aSayHi = () => the sayHi ( 'A', 'Hi')
const aSayGoodbye = ( ) => the sayHi ( 'A', 'Goodbye')
const aSayFuck = () => the sayHi ( 'A', 'Fuck'
) Copy the code of course this is a very simple scenario, if the function argument passed sayHi there are many, but there are a number of repeat words, the code redundancy. At this time, we need to use partial function optimization:
const Asay = (name) => the sayHi ( 'A', name)
const aSayHi = () => Asay ( 'Hi')
const aSayGoodbye = () => Asay ( 'Goodbye')
const aSayFuck = () => Asay ( 'fuck')
copying the code ternary expressions with shorted together, a few examples
// before
IF (type === to true) {
value =. 1
} the else {
value = 2
}
// After
value type =?. 1 : 2

// before
if (type === DEL) {
this.delateData(id)
} else {
this.addData(id)
}
// after
thistype === DEL ? 'delateData' : 'addData'
// or
;(type === DEL ? this.delateData : this.addData)(id)

Before //
IF (! ARR) {
ARR = []
}
arr.push (Item)
// After that belongs to a eslint not recommended
;. (Arr || (arr = [])) push (item)

Before //
IF (A) {
return C
}
// After
return && C A
final example of copying the code, such as a duplicate key assignment process can be simplified with the variable key
Switch (key) {
Case 'A':
return {A : newVal}
Case 'B':
return {B: newVal}
Case 'C':
return {C: newVal}
}
// After
return {[Key]: newVal}
copy the code HOWEVER, no matter when the familiar multi-code write more well, you must also write comments. The core algorithm, public assemblies, public comment is required particular function
/ **

  • Create a tree organizational structure
  • @param {Object} orgs
  • @param {Array} [parent=[]]
  • @param {Boolean} needs to be checked whether the check
    * /
    copy the code
    Summary: Short Code no duplicates, and watching themselves not greasy; detached logic functions encapsulate common invisible code quality improve. Finally benefits that accelerate the development efficiency, but also enhance the development experience and accomplishment: "Finally not every copy, and looked at his hand and simply elegant code, want to demand more and more of the"

How to make operational requirements are not boring
most of the companies are based on business demand-driven, iterative requirements in addition to the flagship product of his home, the other is usually operational needs as an auxiliary. Class operational requirements, generally have a short-lived, high-frequency characteristics have a deadline.
One operator activities, there may be a variety of modes, a variety of display layouts, a variety of logic, random combination of product operations, according to data adjusted to find the best solution, which is the operational play scenarios --ab test.
Some people Faced with this situation, always sigh: demand has also changed, and nothing has changed with every day, how they change back, you happy enough. In fact, this situation, we just give yourself a good plan way ahead, behind really free to change, do not even need to develop basic
We start with an example of a simple user information page:
the render () {
const {name, the this Score} = .state.info
return (
<main>
<header> {name} </ header>
score: <sectionTop> score {} </ sectionTop>
</ main>
)
}
copy the code increase adaptation layer
we try not to move the common core logic the code, do not say "just add if it." The introduction of new code, may introduce other bug (one of the common illusion: I added a line or two, will not cause bug), there are certain risks.
Back to the topic, if you suddenly say this event to pull another game scores directly to the requested change, and then put all the components of the field changed, of course, it is a method. If you change soon finished, go back and change have to say, it is not vomiting blood. Clearly we need an adaptation layer:
function Adapter (the Response, info) {
return Object.keys(newConf).reduce((res, key) => {
res[key] = response[newConf[key]]
return res
}, {})
}
// before
function fetchA() {
return request('/a')
}
fetchA.then(res => {
this.setState({
info: { name: res.nickname, score: res.counts }
})
})

// after the requesting function directly modify
function fetchA () {
return Request ( '/ A'). The then (RES => {
// return the result of the adaptation, when the constant use of external
return adapter (res, {
name: 'Nickname',
Score: 'Counts'
})
})
}
copy the code we adapted to concentrate together, each to be changed, as long as the adaptation layer to change here, can change request interface. Of course, back then, if all unity is the best, but there are historical reasons not changed on a whim of.

If a lot of change to change the interface to do: expand?
At this point, we need to maintain a configuration table, save a request and adaptation objects, rather than directly to get rid of the previous code

cgiMAp = {const
'/ A': {
name: 'Nickname',
Score: 'Counts'
},
// ...
}
copy the code by reading this configuration, a read request logic function inside the package, can be adapted with all the relevant interfaces. If a change behind data sources, that address the needs of the speed of light
function reqGenerator (CFG) {
return Object.keys (CFG) .reduce ((RES, Key) => {
RES [key.slice (. 1)] = ( ) => Request (Key) .then (R & lt => Adapter (R & lt, CFG [Key]))
return RES
}, {})
}
const = reqGenerator reqs (cgiMAp)
reqs.a ()
to copy the code components of strict compliance

For example in front of the user's information page, if the user information page requires more content to fill it, if you do not want to show the score it?

This case, first and confirm the product side, what is the future must be and what will become. Changing portion will, we directly use the content time coming:
class the App the extends the Component {
// ...
the render () {
const {name, Score = this.state.info}
return (
<main>
<header> {name} </ header>
<sectionTop> this.props.children {} </ sectionTop>
score: <sectionTop> score {} </ sectionTop>
</ main>
)
}
}
copy the code this way, as long as the upper assembly encases personalization component content on the ok
<App>
<Section> I'm just a trainee </ Section>
<ul>
<li> sing </ li>
<li> jump </ li>
<li> RAP </ li>
</ ul>
< / App>


const [IS_NO_JOIN, IS_PAY, IS_SCORE_HIGH] = [1, 2, 3]
const MAP = {

}
function Header(props) {
const [type, setType] = useState('normal')
useEffect(() => {
// 用名字获取用户身份
requestTypeByName(props.children).then(res => {
setType(res.type)
})
}, [])
return (
<header
className={classnames(MAP[type])}

props.children} {
</ header>
)
}
copy the code or not fixed core logic, rendering the structure and sequence does not move. More customization features, from the top of our parent component control, rendering control logic, display components, copywriting and so on display, the upper parent component assembled good, passing through props core components. This process is the core rendering logic such as writing before a colleague. Header components are written in a, b colleague is not responsible for this, but b is the demand of developers, so should render good posture adjustment, adaptation, injected into a colleague wrote to the core logic components. The final performance is give control to the b, b to make change, this way is less invasive, low risk, and strong expansion of a scheme.

"The success dumped a pot", a document the training and preparation b, and b after completion logical explanation laughs off work - this is a more elegant and secure solutions, we all understand

Anti-forward point of view, if to make a change (assuming that the core module is a huge complex and can not live only by the quick start to a hold of):
// add style row n
// add processing logic state, and can not add business logic affect the original logic change was cautiously
@ adapted to change field, and a few lines of
the render () {
const {name, Score = this.state.info}
return (
<main>
<header className = "XXX"> {name } </ header>
<Section> {this.props.children} </ Section>
score: <Section> {score} </ Section>
</ main>
)
}
// the After Coding: of MMP, Why should I need b help me, I have to start from scratch to see and understand the needs of demand
copy the code
change over, on the line, suddenly the operator said there behind, or to seek a heart xxx .... At this shaded area

Operations configure the interface
previous example, we are doing very little change is complete. Of course a change each digit to change words, the front end will be released, this is not an elegant solution. So the final solution should be, this part of the configuration pulled out, so that one operator on the platform configuration, front-end interface to read through the configuration of the platform back to render the page. Operators need to change, we just need to put on the platform configuration modifications.
// write so arranged on a visualization configuration internet
@ cgiMAp = const {
// '/ A': {
// name: 'Nickname',
// Score: 'Counts'
//},
// // .. .
//}
function reqGenerator (CFG) {
return Object.keys (CFG) .reduce ((RES, Key) => {
RES [key.slice (. 1)] = () => Request (Key) .then (R & lt => Adapter (R & lt, CFG [Key]))
return RES
}, {})
}
Request ( '/ config'). the then (RES => {
const = reqGenerator reqs (res.cgiMAp)
reqs.a ()
})

Copy the code but also consider caching, disaster recovery, improve the look of the page usability, accessibility:

If the interface is hung up, how to enhance the user experience of
how to make a page in the hands, such as monitoring, Buried
how to do robust page, and can withstand the ravages of indiscriminate operation of various machines and users

Finally,
I put down the front label, no matter what is on their own is a kind of growth, in addition to technology, more of a variety of soft skills, methodology, way of thinking. Only to find out the social, coding is perhaps the easiest part of life

Guess you like

Origin blog.51cto.com/14516164/2433634