Loading...

React Framework Summary – Richmond SEO, BC

React Framework Summary – Richmond SEO, BC

React Framework Summary – Richmond SEO, BC

The difference between the three frameworks: React, Angular, and Vue

  • Angular has a relatively strong exclusivity, and
  • React advocates the concept of functional programming. It is not as intrusive as Angular, mainly because it is soft intrusive.
  • Vue progressive

How do you think about react / what is react is a framework, compared to mvc, it is only one of v, it is suitable for the development of large-scale applications with constantly changing data

The advantages of react over other frameworks: High performance and high efficiency realize the high performance and high efficiency development of the front-end interface, so react is very good at handling componentized pages

React vs. Vue – Shopify Expert Vancouver

  1. Similarity:
    1. Use Virtual DOM
    2. Provides reactive (Reactive) and componentized (Composable) view components.
    3. Keep the focus on the core library, and leave other functions such as routing and global state management to the relevant libraries.
  2. the difference:
    1. In a React application, when the state of a component changes, it will re-render the entire component subtree with that component as the root. If you want to avoid unnecessary re-rendering of sub-components, you need to do it manually; in Vue applications, component dependencies are automatically tracked during the rendering process, so the system can know exactly which component needs to be re-rendered, and developers don’t need to consider whether the component needs to be re-rendered and other optimizations.
    2. In React, everything is JavaScript, and the rendering functions of all components rely on JSX. JSX is syntactic sugar for writing JavaScript using XML syntax. You can use the full programming language JavaScript function to build your view page; Vue has its own rendering function, Vue also supports JSX, Vue officially recommends using template rendering view. Components are divided into logical components and presentation components.
    3. CSS within the scope of the component. CSS scope is implemented in React through the CSS-in-JS solution; in Vue, it is implemented by adding scoped tags to style tags.
    4. Vue’s routing library and state management library are both supported by official maintenance and updated synchronously with the core library. React chose to leave these issues to the community for maintenance, thus creating a more decentralized ecosystem.

Features and advantages of React: App Development Vancouver

1. Virtual dom

Virtual DOM is an abstraction layer established on the basis of DOM. Any changes made to data and state will be automatically and efficiently synchronized to the virtual DOM, and finally synchronized to the DOM in batches.

It is a JavaScript object. When re-rendering, it will compare the Virtual DOM generated this time with the Virtual DOM rendered last time. After the difference is found, you only need to touch the part of the difference when you modify the real DOM tree. Use This virtual dom avoids the creation and comparison of native dom, which greatly improves performance, because the creation of native dom is very performance-consuming, and the comparison and creation of js objects has little performance overhead. From this way Provide application performance

2. Components

Componentized components refer to aggregates that contain html, css, js, and image elements at the same time

Each component and component are independent of each other for easy maintenance

The component is created through React.createClass (ES5), in es6 directly through the class keyword to create

The division of components should satisfy the principle of high cohesion and low coupling.

  • High cohesion refers to putting logically closely related content in one component.
  • Low coupling means that the dependencies of different components should be as weak as possible, and each component should be as independent as possible.

The component is actually a constructor, and each use of the component is equivalent to instantiating the component

React components must use the render function to create the virtual dom structure of the component

The component needs to be mounted on a certain node using the ReactDOM.render method

The first letter of the component must be capitalized

3. One-way data flow, data binding, parent to child

4.jsx tree

 

During the rendering process of react, how are the sibling nodes handled? That is, when the key value is different.

Usually when we output nodes, we map an array and return a ReactNode. In order to facilitate the internal optimization of React, we must add a key to each ReactNode. This key prop is not for developers, but for React. Used, the general function is to add an identity to each reactNode to facilitate the identification of react. During the re-rendering process, if the key is the same, if the component property changes, then react only updates the corresponding property of the component; if there is no change, then Do not update. If the keys are different, React destroys the component first, and then recreates the component.

 

When traversing child nodes, do not use index as the key of the component to pass in.

Mainly because react is based on virtual dom and diff algorithm to improve performance, and improving performance means that some dom nodes will be reused. The key is a negative auxiliary diff algorithm. In some cases, index is no problem, for example It is just a loop rendering display, but if there is an operation involving the addition and deletion of intermediate nodes, it will cause React to fail to correctly identify which nodes are deleted and which nodes are added, and many seemingly strange phenomena will occur.

When optimizing the performance of react , for too many deeply nested components, due to the state change of the parent component, the child components are also re-rendered. Pure function components can be used according to the situation. Because pure function components are components without state, they can be used at this time. High-level components encapsulate a function similar to PureComponet to function components

For performance optimization, you can also use React.memo

React.memo It is a new API of React 16.6, used to cache component rendering and avoid unnecessary updates. In fact, it is also a high-level component,  PureComponent very similar to it, but the difference is that it  React.memo can only be used for functional components.

  1. import { memo } from ‘react’;
  2. function Button(props) {
  3. // Component code
  4. }
  5. export default memo(Button);

Advanced usage

By default, it will only make a shallow comparison of props. When encountering a complex object with a deeper level, it will not be able to do what it wants. For a specific business scenario, shouldComponentUpdate an API similar to this may be required  , and then  memo the second parameter is used to achieve:

  1. function arePropsEqual(prevProps, nextProps) {
  2. // your code
  3. return prevProps === nextProps;
  4. }
  5. export default memo(Button, arePropsEqual);

Note: the  shouldComponentUpdate difference is that arePropsEqual the return  true , the trigger will not render, if it returns  false, it will. It’s  shouldComponentUpdate just the opposite.

react-routers

 

There is history on the Router component,

The Route component passes the location and match to the routing component inside,

The Router component passes the history to the routing component

You can monitor the route in the life cycle in the view layer to perform corresponding operations

 

1. When rendering the root component, the router component is wrapped on the outermost layer, and the history attribute can be set on it. The value can be hashHistory||browserHistory

When the value is hashHistory, the change of the url is the change of the hash value, and the router will detect the change of the hash to realize the switch of the component

When the value is browserHistory, the change of url is the change of path, which requires back-end configuration

 

2. Where you need to switch routing components, use this.props.children to indicate the corresponding routing components

 

3. Route can be nested multiple times in Route to achieve multi-level routing

 

4. Use the Redirect component to immediately redirect from one route to other routes. With this attribute, when our form is set to’*’, the unmatched route can be redirected to a certain route.

<Redirect from=”*” to=”home”/>

 

4. You can add /:param to the path when configuring Route to indicate that this route requires parameters

When it is passed in, the querystring parameter can be passed in and set in the query in the Link. In the target component, the parameters are received through params, routePrams, location, etc. in this.props

 

5. Programmatic Navigation

* Obtain the history object through this.props.history in the routing component, and use the push, replace, go, and goBack methods to perform implicit jumps

* BrowserHistory or hashHistory can be imported from react-router to call the push, replace, go, and goBack methods to perform implicit jumps

 

6. You can monitor routing changes by setting the onLeave and onEnter routing hooks on the routing configuration

 

router3 4 difference

1) In V3, it is generally used, but the implementation is specified in its history attribute: hashHistory or browserHistory. In v4, you need to directly use specific implementations, such as HashRouter or BrowserRouter:

(2) In V3, the use of nested Route and Index Route is very common. IndexRoute is gone in v4, and Route nesting is not allowed.

(3) In v3, the definition of Router is generally global, and all routes are defined in one file; in v4, Router can appear in any component.

(4) In v3, you can get the parameters passed in the URL from the params attribute. For example, when I get the bloggerID in BlogLayout, this attribute is no longer automatically injected in v4 and needs to be obtained from the match attribute.

(5) In v3, I can use Route’s onEnter, onUpdate and onLeave events to do something. In v4, Route events are gone. The solution is to use the HOC withRouter (High-Order Components)

 

react- redux S: using a react-redux redux libraries using such a cleaner, which provides the provider and connect method

react-redux divides all components into two categories, put Provider on the outside and pass it to store connect for connection

UI components have the following characteristics.

* Only responsible for the presentation of the UI, without any business logic

* No state (that is, this.state variable is not used)

* All data are provided by parameters (this.props)

* Does not use any Redux API

 

The characteristics of container components are just the opposite.

* Responsible for managing data and business logic, not for UI presentation

* With internal status

* Use Redux API

 

Just remember one sentence: UI components are responsible for the presentation of UI, and container components are responsible for managing data and logic.

connect() can generate a high-level component, which can generate a new container component after receiving a UI component

* Provider Provider is to pass the store we created with rudux to other internal components. Allow internal components to enjoy this store and provide updates to the state.

It is achieved by using the context tree, placing the store on the context tree, and then all the internal container components use the store on the context tree through this.context.store

* connect is a function, this function receives the mapStateToProps, mapDispatchToProps properties, connect will return a high-level component, in this high-level component receiving UI components, returning a new component is the container component, because of the closure feature, so the container The component can use the mapStateToProps and mapDispatchToProps properties passed in in connect, and then the container component can take out the store placed by the Provider from the context tree, and then use mapStateToProps and mapDispatchToProps to pass the state and the dispatch method to the UI component, as the store data When it changes, the container component will render and re-pass the latest state to the UI component

The role of dispatch The role of middleware is to allow the actionCreator method to return a function that can receive dispatch, in which you can do some asynchronous operations

redux (subsequent update of the detailed documentation of redux)

Disadvantages: All data of a component must be passed by the parent component. When the related data of a component is updated, the parent element does not need to use the component in time, and the parent component will still be rendered again, which may affect efficiency.

Projects that need to use redux:

  • The state of a component needs to be shared
  • A certain state needs to be available anywhere
  • A component needs to change the global state
  • One component needs to change the state of another component

step:

  • Create store through createStore and bind reducer to it
  • The reducer can return a new data every time, synchronized to the state of the store
  • Get the state through store.getState() in the view
  • When you want to update the data, that is, the user generates an operation, call the actionCreator method to generate the action and pass it to the reducer
  • The reducer returns a new state. When the state of the store is changed to a new state by the reducer, the callback function in the store.subscribe method will be executed (executed in the life cycle), and the view can be notified to re-obtain the state at this time

> Note: Redux does not have to be used with react, because flux and redux are a complete architecture. In react, only the components of react are used as the view layer in redux.

 

Partition reducer

Because there can only be one large state in an application, the code in the reducer will be particularly special, then you can use the combineReducers method to merge the separated reducers together

 

applyMiddleware (thunk)//Use middleware

The role of this middleware here is to allow the actionCreator method to return a function that can receive dispatch, in this function

You can do some asynchronous operations

react lifecycle process

#####Initialization phase

  • constructor: The constructor is executed first, usually in the constructor to initialize the state object or bind this to a custom method
  • getDerivedStateFromProps: static getDerivedStateFromProps(nextProps, prevState), this is a static method. When we receive new properties and want to modify our state, we can use getDerivedStateFromProps.
  • render: The render function is a pure function that only returns what needs to be rendered. It should not contain other business logic. It can return content such as native DOM, React components, Fragments, Portals, strings and numbers.
  • componentDidMount: Called after the component is loaded. At this time, we can get the DOM node and operate it, such as Canvas, SVG, etc. Server requests and subscriptions can be written in this, but remember to cancel the subscription in componentWillUnmount.

##### Running phase

  • getDerivedStateFromProps: This method will also be called during the update phase.
  • shouldComponentUpdate: shouldComponentUpdate(nextProps, nextState), there are two parameters, which represent the new property and the state after the change, and return a Boolean value. If it is true, it means re-rendering will be triggered, false means it will not trigger re-rendering, and it returns true by default. You can use this life cycle to optimize React program performance.
  • Render: Same as render during the mount phase.
  • getSnapshotBeforeUpdate: getSnapshotBeforeUpdate(prevProps, prevState). This method will be called after render and before componentDidUpdate. It has two parameters, which represent the previous properties and the previous state. This function has a return value, which will be passed to componentDidUpdate as the third parameter. If the return value is not needed, null can be returned. This method must be used in conjunction with componentDidUpdate.
  • componentDidUpdate: componentDidUpdate(prevProps, prevState, snapshot), called after getSnapshotBeforeUpdate, there are three parameters, representing the previous props, the previous state, and the snapshot. The parameter snapshot is returned by getSnapshotBeforeUpdate. If the state of the DOM element is needed when triggering some callback functions, the comparison or calculation process will be migrated to getSnapshotBeforeUpdate, and then the callback or update state will be triggered uniformly in componentDidUpdate.

##### Destruction phase

The moment before the component is destroyed, componentWillUnmount will be triggered,

Do some aftermath work. For example, when you switch the route, the previous route is still requesting data but you have destroyed that component. At this time, you will be warned that you cannot get data from the already destroyed component, so you can set a switch when it is destroyed. Time to stop fetching data

##### Error handling

 

When an error is thrown in the rendering process, life cycle, or sub-component constructor, the following methods are called:

  • static getDerivedStateFromError()
  • componentDidCatch()

The high-level component is a function that receives a component that is not a route and returns a new component, so that some APIs can be added to the new component to realize code reuse
and stateless components:

  1. function Faaa(props){
  2.     return (
  3.         <div></div>
  4.     )
  5. }

 How does react take out the real dom from the virtual dom? (ref)

  1. // react怎么从虚拟dom中拿出真实dom?(ref)
  2. var MyComponent = React.createClass({
  3. handleClick: function() {
  4. this.refs.myTextInput.focus();
  5. },
  6. render: function() {
  7. return (
  8. <div>
  9. <input type=“text” ref=“myTextInput” />
  10. <input type=“button” value=“Focus the text input” onClick={this.handleClick} />
  11. </div>
  12. );
  13. }
  14. });

React grammar specification

  • {...this.props} (Don’t abuse it. Please only pass the props needed by the component. Passing too much or too deep will increase the burden on the data in shouldComponentUpdate. Therefore, please use spread attributes (<Component {…props} / >)).
  • ::this.handleChange(). (Please place the bind of the method in the constructor)
  • this.handleChange.bind(this,id)
  • Do not write complex pages in one component.
  • Please use as much as possible const element.
  • Add key to the map, and don’t use index (variable) for key.
  • Minimize the use setTimeOutor uncontrollable refs and DOM operations.
  • propsAnd statethe data is as simple, clear and flat as possible.
  • Use return nullinstead of CSS display:noneto control the display and hide of the node. Ensure that there are as few DOM nodes as possible on the page at the same time.

React this.props.children – Vancouver SEO Service Provider

The properties of the this.props object correspond to the properties of the component one-to-one, but there is one exception, that is, this.props.childrenproperties. It represents all the child nodes of the component.

It should be noted here that this.props.childrenthere are three possibilities for the value of: if the current component has no child nodes, it is undefined; if there is one child node, the data type is Object; if there are multiple child nodes, the data type is array. So, this.props.childrenbe careful when handling .

React provides a tool method React.Childrento deal with this.props.children. We can use React.Children.mapto traverse the child nodes, without worrying about this.props.childrendata types is undefinedstill object.

 

The architectural difference between React15 and React16 and React17

The React 15 architecture is divided into two parts:

  1. Reconciler (coordinator): find out the changed components. Use the diff algorithm to find out the changed components and submit them to the Renderer renderer.
  2. Renderer: Re-render the changed components.

Diff mechanism : First, the Reconciler (coordinator) calculates the components that need to be updated through the diff algorithm, and then uses the Renderer (renderer) to perform the update and render the components. Then the Reconciler continues to calculate the components that need to be updated, and the Renderer continues to update the rendering. The whole process is synchronous, and Reconciler and Renderer alternate. And it uses recursive implementation, so it can’t be interrupted.

 

The React 16 architecture is divided into three parts:

  1. Scheduler (Scheduler): scheduling task priority, so that the high priority tasks enter the Reconciler.
  2. Reconciler: Responsible for finding the changed components. Use the diff algorithm to find out the changed components and submit them to the Renderer renderer.
  3. Renderer: Responsible for re-rendering changed components.

Diff mechanism : First, the Scheduler (scheduler) to schedule the priority of the task, and the higher priority task is added to the Reconciler (coordinator) . The Reconciler (coordinator) calculates the components that need to be updated through the diff algorithm and marks the update status . After the entire component is updated , the Renderer is used to perform the update and render the component.

 

React17:

No new features have been added,

Change 1: Event delegate no longer hangs on the document

The main problem with the previous coexistence of multiple versions is the default delegation mechanism of the React event system . For performance reasons, React will only hook documentup event listeners. After the DOM event is triggered, it will bubble up document. React finds the corresponding component and creates a React event. And simulate the event bubbling according to the component tree (the native DOM event has already emerged at this time document):

Therefore, when different versions of React components are used in nested applications, they e.stopPropagation()cannot work properly (the two different versions of the event system are independent, and it’s documenttoo late)

The React17 solve this problem, React 17 not to documenthang event delegate, but linked to the DOM container

On the other hand, documentretracting the event system from it also makes it easier for React to coexist with other technology stacks (at least there are fewer differences in the event mechanism)

Change 2: Move closer to browser native events

  • onScroll no longer bubbling
  • onFocus/onBlur directly uses native focusin/focusout events
  • The event monitoring in the capture phase directly uses the native DOM event monitoring mechanism

Note that onFocus/onBlurthe switching of the lower-level implementation scheme does not affect bubbling, that is, the ones in React onFocuswill still bubbling (and do not plan to change, I think this feature is very useful)

Change 3: DOM event reuse pool is abandoned

For performance reasons, in order to reuse SyntheticEvent, an event pool was maintained. As a result, React events are only available during the propagation process, and then they will be recycled and released immediately , for example:

  1. <button onClick={(e) => {
  2. console.log(e.target.nodeName);
  3. // 输出 BUTTON
  4. // e.persist();
  5. setTimeout(() => {
  6. // 报错 Uncaught TypeError: Cannot read property ‘nodeName’ of null
  7. console.log(e.target.nodeName);
  8. });
  9. }}>
  10. Click Me!
  11. </button>

All states on the event object outside the propagation process will be set to null, unless manually e.persist()(or directly do value caching)

React 17 removes the event reuse mechanism , because this performance optimization is meaningless in modern browsers, but it brings troubles to developers.

 

Change 4: Effect Hook cleanup operation is changed to asynchronous execution

useEffect itself is executed asynchronously, but its cleanup work is executed synchronously (just like the synchronous execution of the Class component componentWillUnmount), which may slow down scenes such as Tab, so React 17 changes to perform cleanup work asynchronously:

  1. useEffect(() => {
  2. // This is the effect itself.
  3. return () => {
  4. // 以前同步执行,React 17之后改为异步执行
  5. // This is its cleanup.
  6. };
  7. });

At the same time, the execution order of the cleanup function is corrected and executed in the order on the component tree (the order was not strictly guaranteed before)

What happened after calling setState? – App Developer Vancouver

After calling setState in the code, React merges the passed parameter object with the current state of the component, triggering the so-called reconciliation process (Reconciliation).

After the reconciliation process, React will construct the React element tree based on the new state in a relatively efficient manner and proceed to re-render the entire UI interface.

After React gets the element tree, React will automatically calculate the node difference between the new tree and the old tree, and then minimize the interface based on the difference and re-render it.

In the difference calculation algorithm (Diff), React can relatively accurately know which locations have changed and how the UK has changed, ensuring on-demand updates instead of re-rendering.

simply put:

  1. Combine parameter objects to trigger the reconciliation process
  2. Calculate the difference between the new tree and the old tree (Diff)
  3. Minimize re-rendering based on the difference

Is setState synchronous or asynchronous?

Answer: Sometimes synchronous, sometimes asynchronous.

  1. setState is asynchronous in synthetic events and hook functions, and synchronous in native events and setTimeout.
  2. The asynchrony of setState does not mean that it is implemented internally by asynchronous code. Its execution process and code are synchronous. It is just that the call sequence of synthetic events and hook functions is updated before it is updated, which makes it impossible to get them immediately in synthetic events and hook functions. The updated value forms the so-called asynchronous.
  3. setState can get the updated result in the callback method through the second parameter setState(partialState, callback).

 

Some plugins of webpack, how to use webpack to optimize the project.

It happens to be doing webpack build optimization and performance optimization recently. For plug-ins, please see the webpack plug-in summary.

Build optimization:

  1. Reduce compilation volume ContextReplacementPugin, IgnorePlugin, babel-plugin-import, babel-plugin-transform-runtime
  2. Parallel compilation happypack, thread-loader, uglifyjsWebpackPlugin open parallel
  3. Cache cache-loader, hard-source-webpack-plugin, uglifyjsWebpackPlugin enable caching, babel-loader enable caching
  4. Pre-compiled dllWebpackPlugin && DllReferencePlugin, auto-dll-webapck-plugin

Performance optimization:

  1. Reduce compilation volume Tree-shaking, Scope Hositing
  2. hash cache webpack-md5-plugin
  3. Unpack splitChunksPlugin, import(), require.ensure

Dependencies needed for installation

redux/react-redux/redux-thunk

node-sass/sass-loader

axios

 

babel-loader for transcoding

css-loader packs css files

style-loader adds styles to the DOM

url-loader pictures are automatically converted into base64 encoded

 

Some package commands when refactoring the project

Build react scaffold
npm install -g create-react-app install scaffold globally
npm install -g yarn install yarn globally
create-react-app project create project project
cd project enter project project
yarn start run project
yarn remove xxx is equivalent to npm uninstall xxx — save Uninstall the specified package
yarn add sass-loader node-sass –save-dev Install sass and configuration (now the new version of webpack should automatically configure sass)
https://www.cnblogs.com/ye-hcj/p/7753085 .html
yarn add redux –save install redux
yarn add react-redux –save install react-redux
yarn add react-router-dom –save install router
yarn add redux-thunk –save install react-thunk
yarn add antd- mobile –save

Regarding the file packaging path problem
Solution: add a sentence in the package.json configuration file: “homepage”: “.”,

  1. function ActionLink() {
  2. function handleClick(e) {
  3. e.preventDefault(); // 
  4. console.log(‘The link was clicked.’);
  5. }
  6. return (
  7. <a href=“#” onClick={handleClick}>
  8. Click me
  9. </a>
  10. );
  11. }
  12. onClick constructor bindthis
  13. event.preventDefault();
  14. react props
  15. this.textInput = React.createRef() ref
  16. this.textInput.current.focus(); dom
  17. <input type=“text” ref={this.textInput} /> ref

The antd configuration is loaded in the config file on demand

  1. plugins: [
  2. [
  3. require.resolve(‘babel-plugin-named-asset-import’),
  4. {
  5. loaderMap: {
  6. svg: {
  7. ReactComponent: ‘@svgr/webpack?-prettier,-svgo![path]’,
  8. },
  9. },
  10. },
  11. ],
  12. [‘import’, { libraryName: “antd”, style: ‘css’ }] // 

Leave a Reply

Your email address will not be published.