41. If you need to optimize react performance (generally not needed) if both state and props of a component are simple types, you can inherit PureComponent instead of Component import { Component, PureComponent } from 'react'; // bad class Message extends Component { render() { return <span>{this.state.message}</span>; } } // good class Message extends PureComponent { render() { return <span>{this.state.message}</span>; } } override the shouldComponentUpdate method to determine whether re-rendering is needed in shouldComponentUpdate based on whether the state,props has changed. If the component inherits PureComponent, there is no need to override the shouldComponentUpdate method import { isReactPropsEqual, isReactStateEqual } from '@fe/common/lib/equal'; shouldComponentUpdate(nextProps:IProps, nextState:IState) { if (isReactStateEqual(nextState,this.state) && isReactPropsEqual(nextProps,this.props)) { return false; } return true; } 42. Event event object type many friends have used ts for a long time, but they don't know the common Event event object types: ClipboardEvent Clipboard event object DragEvent drag event object ChangeEvent Change event object KeyboardEvent keyboard event object MouseEvent mouse event object TouchEvent Touch event object WheelEvent wheel event object AnimationEvent animated event object TransitionEvent transition event object import { MouseEvent } from 'react'; interface IProps { onClick(event: MouseEvent<HTMLDivElement>): void; } 43. Replace state status with private attributes for some status attributes that do not need to control ui, we can bind them directly to this, that is, private attributes. There is no need to apply them to this.state, otherwise the rendering mechanism will be triggered and performance will be wasted. For example, when we request paging data, we will have a variable. // bad state: IState = { pageNo:1, pageSize:10 };…

March 30, 2023 0comments 1328hotness 0likes Aaron Read all

31. SetState may be synchronous setState is "asynchronous" in compositing events and hook functions in react. setState is synchronized in native events and setTimeout. 32. Do not add await before setState setState can also be preceded by await and become synchronized, but it is a coincidence that we are not sure which version will not support it in the future. In order to follow the design principles of the react framework, we use the form of drop function. // bad func = async (name, value, status) => { await this.setState({ name }); // TODO }; // good func = (name, value, status) => { this.setState( { name }, () => { // TODO } ); }; 33. Block event default behavior you cannot block the default behavior in React by returning false. PreventDefault must be explicitly called. 34. A function that removes side effects in componentWillUnmount clear EventListener abort a data request clear timer 35. key for key optimization in components, maximize reuse of dom //bad this.state.dataAry.map((item, index) => { return <span key={index} />; }); //good this.state.dataAry.map(item => <span key={item.id} />); 36. There must be hasOwnProperty judgment in for-in (that is, it is forbidden to read the properties of prototype objects directly) //bad const arr = []; const key = ''; for (key in obj) { arr.push(obj[key]); } //good const arr = []; const key = ''; for (key in obj) { if (obj.hasOwnProperty(key)) { arr.push(obj[key]); } } 37. The use of third-party library functions wrapped in try catch to prevent errors in the third-party library, causing the whole program…

March 30, 2023 0comments 1331hotness 0likes Aaron Read all

21. Simple components can use functions instead of // bad class Listing extends React.Component { render() { return <div>{this.props.hello}</div>; } } // good function Listing({ hello }) { return <div>{hello}</div>; } 22. Cache commonly used attributes // bad this.props.app.openid; this.state.time // good const { app } = this.props; const { time } = this.state; console.log(app.openid) 23. The input input box uses trim () // bad let searchContent = form.search.value; // good let searchContent = form.search.value.trim(); 24. You need to escape before using location jump // bad window.location.href = redirectUrl + '?a=10&b=20'; // good window.location.href = redirectUrl + encodeURIComponent('?a=10&b=20'); 25. Use react-router // bad import { withRouter, RouteComponentProps } from 'react-router-dom'; export interface IProps extends RouteComponentProps<any> {} class App extends React.Component<IProps, AppStates> {} export default withRouter(App); // good import { withRouter, RouteComponentProps } from 'react-router-dom'; class App extends React.Component<IProps & RouteComponentProps<{}>, AppStates> {} export default withRouter(App); 26. Simultaneous development, data request api directory git conflict directory scheme create a new directory under the api directory. The directory corresponds to the first-level tab, and an index.js is placed in this directory. Finally, all the api requests used by the second-level tab components are introduced into this index.js. // at present |- api |- pageA.ts |- pageB.ts // propose |- api |- pageA |- index.js |- aaa.js |- bbb.js |- pageB |- index.js |- aaa.js |- bbb.js |- ccc.js 27. Components are too deeply nested components generally do not exceed three or four layers at most. Too deep levels may lead to data transfer too deep. When doing some fine-grained operations, it is…

March 30, 2023 0comments 1282hotness 0likes Aaron Read all

11. Type assertion // bad function getLength(something: string | number): number { return something.length; } // index.ts(2,22): error TS2339: Property 'length' does not exist on type 'string | number'. // Property 'length' does not exist on type 'number'. // bad function getLength(something: string | number): number { if ((<string>something).length) { return (<string>something).length; } else { return something.toString().length; } } // good function getLength(something: string | number): number { if (typeof something === 'string') { return something.length; } else { return something.toString().length; } } 12. Interface declaration order there are four kinds of daily use: read-only parameters first, required parameters second, optional parameters second, uncertain parameters last interface iProps { readonly x: number; readonly y: number; name: string; age: number; height?: number; [propName: string]: any; } 13. Ts useful tools generics Record uses this to declare the type of object structure Used to define a javascript object. Key is a string, and value is of any type const people:Record<string,any> = { name: 'chengfeng', age: 10 } Partial is used to make incoming properties optional. interface iPeople { title: string; name: string; } const people: Partial<iPeople> = { title: 'Delete inactive users', }; The defined structure can be any of the interfaces iPeoplekey The function of Readonly is to make the incoming property read-only interface iPeople { title: string; name: string; } const people: Readonly<Todo> = { title: 'todo list', name: chenfeng; }; The title name attribute is read-only The function of Required is to make the passed property a required option interface iPeople { title?: string; name?: string; } const people1:…

March 30, 2023 0comments 1326hotness 0likes Aaron Read all

there is no distinction between right and wrong, and there must be some imperfections, combining my daily development and experience. It allows you to write more rigorous code, and I hope it will be helpful after reading it. 1. Comments (1) comments at the top of the file, including description, author, date /** * @description xxxxxx * @author chengfeng * @since 19/05/21 */ (2) comments on the module /** * Copy Data * @param {*} data Source data to copy * @param {boolean} [isDeep=false] Is it a deep copy? Default is a shallow copy * @return {*} Return copied data */ (3) Business code comments /*Business Code Comment*/ (4) variable comments interface IState { // Name name: string; // Telephone phone: number; // Address address: string; } 2. Reference component order first reference the external component library, then the current component block level component, then the common function library in common, and finally the css style import * as React from 'react'; import { Dropdown, Menu, Icon } from 'antd'; import Header from './Header'; import toast from 'common/toast'; import './index.less'; 3. Quotation marks use single quotes, or backquotes of es6 4. Indent use two spaces const handleCheck = () => { onCancel && onCancel(); onClose && onClose(); }; 5. Semicolon every expression except for a code block must be followed by a semicolon. 6. Parentheses the following keywords must be followed by curly braces (even if the content of the code block is only one line): if, else, for, while, do, switch, try, catch, finally, with. // not good if…

March 30, 2023 0comments 1318hotness 0likes Aaron Read all

case 3: Hooks about time here we mainly introduce three hooks about time: useTimeout , useInterval and useCountDown useTimeout useTimeout : execute once in a period of time pass parameters as long as the function and delay time are needed. It is important to note that when unloading, OK the timer after clearing it detailed code: import { useEffect } from 'react'; import useLatest from '../useLatest'; const useTimeout = (fn:() => void, delay?: number): void => { const fnRef = useLatest(fn) useEffect(() => { if(!delay || delay < 0) return; const timer = setTimeout(() => { fnRef.current(); }, delay) return () => { clearTimeout(timer) } }, [delay]) }; export default useTimeout; useInterval useInterval : execute every time is roughly the same as useTimeout , with an extra parameter of whether to render for the first time immediate detailed code: import { useEffect } from 'react'; import useLatest from '../useLatest'; const useInterval = (fn:() => void, delay?: number, immediate?:boolean): void => { const fnRef = useLatest(fn) useEffect(() => { if(!delay || delay < 0) return; if(immediate) fnRef.current(); const timer = setInterval(() => { fnRef.current(); }, delay) return () => { clearInterval(timer) } }, [delay]) }; export default useInterval; useCountDown useCountDown : hooks that simply control the countdown as before, let's think about what this hook needs: the hook for countdown first needs a target time (targetDate), controls the number of seconds of time change (interval defaults to 1s), and then is the function (onEnd) triggered after the countdown is completed The return parameter of is more clear at a glance. It…

March 30, 2023 0comments 1404hotness 0likes Aaron Read all

case case 1: useReactive useReactive : a useState with responsive reason: we know that variables can be defined in the format with useState const [count, setCount] = useState<number>(0) set it through setCount , and get it by count . Only in this way can the view be rendered Let's take a look at the normal operation, like this let count = 0; count = 7 the value of count is 7, that is to say, the data is responsive so can we also write useState as responsive ? I am free to set the value of count, and I can get the latest value of count at any time, instead of setting it through setCount . Let's think about how to implement a useState with responsive characteristics, that is, useRective If you are interested in the following questions, you can think for yourself first: how to set the import and export parameters of this hook? how to make the data responsive (after all, normal operations can't refresh the view)? how do I use TS to write and refine its type? how to optimize it better? analyze the key of the above four small questions is the second . How do we make the data responsive ? if we want to make it responsive, we must monitor the change of the value and make changes, that is to say, when we operate on this number, we need to intercept intercept . Then we need a knowledge point of ES6 : Proxy the points of Proxy and Reflect will be used here…

March 30, 2023 0comments 1350hotness 0likes Aaron Read all

encapsulate useCreation with useMemo and useRef useCreation : is a substitute for useMemo or useRef . In other words, the useCreation hook enhances useMemo and useRef so that the hook can replace the two hooks. (from ahooks-useCreation) useMemo is not necessarily the latest value, but useCreation ensures that the value you get must be the latest value for the creation of complex constants, useRef is prone to potential performance risks, but useCreation can avoid the performance hazard here refers to: // Every time you re render, the process of instantiating the Subject is executed, even if the instance is immediately thrown away const a = useRef(new Subject()) //Performance hazards can be avoided through the factory function const b = useCreation(() => new Subject(), []) undefined next let's look at how to encapsulate a useCreation . First, we need to understand the following three points: the first point: determine the parameters first. The parameters of useCreation are the same as those of useMemo . The first parameter is a function, and the second parameter is a variable array . second point: our values should be saved in useRef , so that the values can be cached, thus reducing extraneous refreshes the third point: the judgment of updating value, how to determine whether to update the value in useRef by the second parameter. if we understand three things, we can implement a useCreation ourselves. import { useRef } from 'react'; import type { DependencyList } from 'react'; const depsAreSame = (oldDeps: DependencyList, deps: DependencyList):boolean => { if(oldDeps === deps) return true for(let…

March 30, 2023 0comments 1447hotness 0likes Aaron Read all

play React Hooks in the above, we talked about using useMemo to handle extraneous rendering. Next, let's take a look at the magic use of these hooks of React Hooks (it is recommended to be familiar with and use the corresponding React Hooks before you can make a good hook) useMemo when a child component is called in a parent component, the state of the parent component changes, causing the parent component to update, while the child component is updated even though it has not changed. to put it simply, when the content of a page is very complex and there are many modules, functional components will be updated from beginning to end . As long as there is a change, all modules will be refreshed, which is obviously not necessary. our ideal state is that each module only updates itself and does not influence each other, so using useMemo is the best solution at this time. pay particular attention here. as long as the status of the parent component is updated, the child component will update regardless of whether the self-component is operated or not . useMemo is to prevent this before we talk about useMemo , let's talk about memo , memo . The function of combines the pure components of pureComponent and the function of componentShouldUpdate . It compares the passed props, and then further determines which props needs to be updated according to the return value of the second function. (specific use will be discussed below) The concept of useMemo is similar to that of memo…

March 30, 2023 0comments 1317hotness 0likes Aaron Read all

React Hooks has been released for more than three years, and it has brought life cycle to functional components. Now, Hooks is gradually replacing class components. I believe that React development partners have a deep understanding, but do you really fully master hooks? Do you know how to make a good custom hooks? We know that React Hooks has useState setting variables, useEffect side effects, useRef to get all the attributes of the element, useMemo , useCallback to optimize performance, and of course a custom Hooks to create the Hooks you want. next let's take a look at the following questions and ask ourselves if we know all of them: What is the origin of Hooks? What is the advanced usage of useRef ? useMemo and useCallback how are they optimized? how to design a good custom Hooks? how to make a custom Hooks that doesn't need useState to modify properties and refresh views directly? how do I make a custom Hooks that can listen for any event? if you have questions and curiosity about the above questions, then this article should be able to help you. this article will answer the above questions by introducing custom Hooks , and demonstrate in the form of case columns with hooks in TS , ahooks . Note: the custom hook described here may be slightly different from that on ahooks , and will not be considered too much. If it is used in a project, it is recommended to directly use the hook on ahooks . what is a custom Hooks? react-hooks…

March 30, 2023 0comments 1317hotness 0likes Aaron Read all
12