React 2019, 17 face questions and frequency Detailed

The following questions from github project front-end interview guide, where there are more than 200 high-frequency front end face of questions and answers, now has 1400star.

Why use a frame instead of native?
Benefits framework:

Components of: which components of React most thorough, even atomic component may be a function of the level, the height of the components of our project can be easy to maintain, easy to expand the portfolio.
Natural stratification: most of the times is that the code JQuery spaghetti code coupling serious, modern framework regardless of MVC, MVP or MVVM pattern can help us stratify, decoupling the code easier to read and write.
Ecology: Now the mainstream front-end frame comes with ecological, whether it is data flow management architecture or UI library has a mature solution.
Development Efficiency: Modern front-end frame by default automatically updated DOM, rather than our manual operation, the liberation of the manual DOM developer's cost, improve development efficiency to solve the UI and state synchronization problem fundamentally.
How virtual DOM merits?
Advantages :

Guarantee the performance limit: virtual DOM can find the smallest differences through diff, and then perform batch patch, although not manually optimize this operation, but much better than the rough DOM manipulation performance, virtual DOM can guarantee that the lower limit of performance
without manual operation DOM: DOM of virtual diff and patch are carried out in an automatic update, we do not need to manually operate DOM, greatly improve the efficiency of the development
of cross-platform: virtual DOM is essentially a JavaScript object, DOM strongly associated with the platform, compared to the virtual DOM can operate more easily across platforms, such as servers rendering, mobile terminal development, etc.
Cons:

We can not be the ultimate optimization: Virtual DOM can not be targeted to optimize the ultimate in extreme performance requirements of some applications, such as direct manual operation VScode DOM way extreme performance optimization
virtual DOM implementation principles?
Virtual DOM is essentially a JavaScript object , it is a true abstract of DOM
state changes, recording new trees and old trees differences
last update to the discrepancy in the real dom
virtual DOM principle

React latest life cycle of what?
There are three life cycle was abandoned (but not removed) after React 16

componentWillMount
componentWillReceiveProps
componentWillUpdate
official plans to release 17 to completely remove these three functions, retaining only three functions UNSAVE_ prefix, the purpose is for backwards compatibility, but for developers should try to avoid using them, but the use of new lifecycle functions in their place

Currently React 16.8 + life cycle is divided into three stages, each stage is mounted, updating stage, unloading phase

Mount the stage:

constructor: constructor, the first to be executed, we usually initialization state objects in the constructor or a custom method to bind the this
getDerivedStateFromProps: static getDerivedStateFromProps (nextProps, PrevState), this is a static method, when we receive new property wanted to modify our state, can be used getDerivedStateFromProps
the render: the render function is a pure function, returns only need to render things should not include other business logic, you can return to native DOM, React components, Fragment, Portals, strings and numbers, Boolean and null and so
componentDidMount: after loading component calls, then we can get to DOM nodes and operations, such as on the canvas, svg operations, server requests, subscriptions can be written on the inside, but remember to unsubscribe componentWillUnmount the
update phase :

getDerivedStateFromProps: This method updates a mount stage may call
shouldComponentUpdate: shouldComponentUpdate (nextProps, nextState) , there are two parameters nextProps and nextState, represents the state after the new properties and changes, returns a Boolean value, true that it would trigger re-rendered, false that it would not trigger re-rendering, default returns true, we usually use this program life cycle to optimize performance React
render: update will trigger this life cycle stage
after getSnapshotBeforeUpdate (prevProps, prevState), this method render: getSnapshotBeforeUpdate , componentDidUpdate before calling, there are two parameters prevProps and prevState, and represents property before the previous state, this function has a return value, will be passed as the third parameter componentDidUpdate, if you do not want to return a value, you can return null, this life cycle must be used with componentDidUpdate with
componentDidUpdate: componentDidUpdate (prevProps, prevState, snapshot), the method is called after getSnapshotBeforeUpdate method, there are three parameters prevProp s, prevState, snapshot, represents props, the previous state, and the previous snapshot. The third argument is getSnapshotBeforeUpdate back, you need to use the state of the DOM element if certain trigger callback function, the process will be calculated contrast or migrate to getSnapshotBeforeUpdate, then trigger callback or update a unified state in componentDidUpdate in.
Unloading phase:

componentWillUnmount: When our component is uninstalled or destroyed will call, we can remove some of the timer to go in this function, the network canceled the request to clean up invalid DOM elements such as garbage clean-up
2019-07-31-14-30- 17
a view of the life cycle react website

React request should be placed in which the life cycle?
Asynchronous React request which should be placed in the end of life cycle, some people think that can be performed in componentWillMount asynchronous requests in advance to avoid black and white, in fact, this view is problematic.

Due to the nature of asynchronous events in JavaScript, when you start the API call, the browser will return to perform other work in the meantime. When React to render a component that does not wait for it to finish componentWillMount anything - React to move forward and continue to render, no way to "pause" Render to wait for data to arrive.

And in componentWillMount request there will be a series of potential problems, first of all, when the server rendering, if the acquired data in componentWillMount years, fetch data will be performed twice, once on the server once the client side, which caused unnecessary requests, secondly, after React Fiber rewritten React 16, componentWillMount may be called multiple times in a single rendering.

The current official recommendation asynchronous request is in componentDidmount in.

If you have special needs need to request in advance, you can also request the constructor in exceptional circumstances:

After react 17 componentWillMount are discarded, only the retention UNSAFE_componentWillMount

setState in the end is asynchronous or synchronous?
First answer: sometimes exhibit asynchronous, synchronous and sometimes exhibit

setState only event in the synthesis and hook function is "asynchronous" in the native events and setTimeout are in sync.
setState of "asynchronous" does not mean that the internal implementation of asynchronous code, in fact, the process and the implementation of the code itself are synchronized, just call the sequence of events and synthesis hook function before the update, resulting in the synthesis of the event and could not immediately hook function get the updated value, forming the so-called "asynchronous", of course, can be the result of the second parameter setState (partialState, callback) callback to get the update.
setState batch update optimization is also built on "asynchronous" (synthetic event, the hook function) will not update the original batch events and setTimeout, in the "asynchronous" If multiple setState of the same value, the setState batch update strategy will be covered, taking the last execution, if it is at the same time setState a number of different values, batch updates will be merged on update.
How to React communication components to achieve?
Between React components of communication:

Parent component to the subassembly correspond: parent may be the sub-assembly by way of transmission props, the communication to the subassembly
subassembly to the parent component Corresponding: props + callback mode, the parent component is passed props for communication to the sub-assembly, this props to act domain parent component itself function, call the function sub-assemblies, sub-assemblies will want information transfer scope as a parameter passed to the parent component of the
brothers components of communication: find common parent of these two sibling nodes, combined with the above two ways forward by the parent node information communication
and inter-level communication: Context is designed to share those is a "global" data for a component tree, such as the current authenticated user, topic or preferred language for multi-span? global data layer by Context communication, but right then
publish a subscription model: publishers publish events, subscribers to listen and react to events, we can communicate through the introduction event module
global status management tools: With Redux or Mobx management tools such as global state communicate, this tool will maintain a global state center Store, and according to With events generate new state
2019-07-31-18-38-37
React to optimize the performance of which is the means?
Many times performance optimization tools are generic front-end performance optimization details, see chapter load

How to React perform assembly / Logic multiplex?
Aside has been officially abandoned Mixin, components Abstract technology currently there are three more mainstream:

Higher-order components:
property broker
reverse inheritance
rendering attributes
react-hooks
component reuse component reuse See Detailed

mixin,, render props, how the pros and cons of the react-hooks hoc?
Mixin flaw:

Implicit (Mixin methods often rely on specific components, but does not know that the definition of component dependencies) between the component and rely on the existence Mixin

Mixin potential conflict between a plurality of (such as defining the same state field)

Mixin tend to add more status, which reduces the predictability of the application (The more state in your application, the harder it is to reason about it.), Resulting in dramatic increase in complexity

Implicit dependence leads to a dependence opaque, maintenance costs and understand the rapidly rising costs:

It is difficult to quickly understand the component behavior, need a comprehensive understanding of all dependent Mixin expansion behavior and interaction between,

Method monovalent group itself and not easily falsified state field, is difficult to determine because it has no dependency Mixin

Mixin is also difficult to maintain, since the last logic Mixin tie will be merged together, it is difficult to figure out a Mixin O

HOC compared Mixin advantages:

Effect HOC through the outer component through the inner assembly Props state, rather than directly changing its State conflict with each other and there is no interference, which reduces the degree of coupling
is different from the tie Mixin + combined, has a natural hierarchy HOC (Component tree structure), which in turn reduces the complexity of
HOC defects:

Scalability limits: State HOC can not access the sub-assembly from the outside can not be filtered out by shouldComponentUpdate unnecessary updates, React provided React.PureComponent after ES6 Class support to solve this problem
Ref delivery problems: Ref been cut off, and later React .forwardRef to solve this problem
Wrapper Hell: the case of multi-layer wrapped HOC components that may arise, multi-layered abstract also increases the complexity and cost understand
naming conflicts: If the higher-order multiple nested assembly, without the use of namespace conflicts would arise and then covering the old attribute
invisibility: HOC corresponds to the original outer repackaging a component assembly, you did not know what is the outer packaging, a black box for you
Render Props advantages:

Render Props HOC above shortcomings can be resolved
Render Props defects:

Cumbersome to use: HOC uses only need the help of decorator syntax is usually a line of code can be multiplexed, Render Props can not do such a simple
nested too deep: Render Props though out of nested components of the problem, but the conversion to the callback function nested
React Hooks advantages:

Simple: React Hooks nesting problems solved and Render Props HOC, and more concise
decoupling: React Hooks can be more easily separated from the UI state and, to achieve a more complete decoupling
combination: Hooks can form a new reference further Hooks the Hooks, combination-changing
function-friendly: React Hooks born as a function component, thereby solving the problem of several major categories of components:
the this point prone to error
logic is divided in different periods so that the code statement difficult to understand and maintain
code reuse cost high (high order component code amount tends to surge)
React Hooks defects:

Additional educational costs (confusion between Functional Component and Class Component)

Restricted (not appear in the conditions, circulating) the writing, and the writing limit increases the cost of reconstruction

Destroyed PureComponent, performance optimization effect React.memo relatively shallow (to get the latest props and state, each render () function must be re-created at the event)

Closures scene may refer to the old state, props value

Internally the intuitive (dependent variable a global state, then no "pure")

React.memo can not completely replace shouldComponentUpdate (because not get the state change, only for props change)

Comments regarding the react-hooks from the official react-hooks RFC

How do you understand the fiber?
React Fiber is the thread scheduling algorithm based browser.

Before React 16, reconcilation is actually a recursive algorithm, it is very difficult to want to interrupt recursion, React 16 before the start using a recursive loop instead.

Fiber: A recocilation (recursive diff), split into numerous small arithmetic task; it can be stopped at any time to restore. Stop the timing of the recovery depends on the current of a (16ms), there is not enough time to allow the calculation.

Fiber Detailed

Time Slice your understanding of?
Time-slicing

React rendering (render), it does not now blocked thread
if your device is fast enough, you will feel the rendering is synchronized
if you device is very slow, you will feel fairly sensitive
, though asynchronous rendering, but you will will see the full rendering, render component rather than a line by line out
the same way as writing component
that is to say, which is behind React to do things for us developers, is transparent, specifically what kind of effect?

There are three charts chart, there is an input box, as well as the above three modes
is very great this component, but also in the input box every time input something, it will go has been rendered. In order to see better performance rendering, Dan has done for us a table.
We take a look, synchronous mode:

In synchronous mode, as we all know, we did not enter a character, React began rendering, when rendering a giant tree React when the card is, why we have appeared shouldUpdate, where Dan also demonstrated, this card!
We look at the second (Debounced mode):

Simple Debounced mode, the rendering is delayed, for example, When you're finished, you start to render all the changes.
The downside is that to do so, at least not blocking the user's input, but there are still very serious Caton.
Switch to asynchronous operation:

Asynchronous rendering mode that does not block the current thread continues to run. In the video where you can see all the input, the table will be forgiven color.
Time slicing is based can be interrupted at any time, restart the Fiber architecture, you can interrupt the current task, prioritize urgent and important task to ensure the smooth running of the page.

? redux workflow
First, we look at a few core concepts:

Store: where to store data, you can see it as a container, the entire application can only have one Store.
State: Store object contains all the data, if want to get data from one point in time, it is necessary to Store a snapshot, a collection of data that point in time, called State.
Action: change of State, will lead to changes in the View. However, users of the reach of State, can only be access to the View. Therefore, the State must be View changes caused. Action is issued notice View, represents State should change to happen.
Action Creator: View how many messages to be sent, how many there will be Action. If you are handwritten, it will be difficult, so we define a function to generate Action, this function is called Action Creator.
Reducer: Store after receipt of Action, we must be given a new State, so that View will change. This calculation is called the State Reducer. Reducer is a function that takes the current State Action and as a parameter and returns a new State.
dispatch: View is the only way to send out the Action.
Then we had at the entire workflow:

First, the user (via View) issuing Action, issued the way it used the dispatch method.
Then, Store automatically call Reducer, and two arguments: Action Current State and received, Reducer will return to the new State
State if there is a change, Store listener function is called to update the View.
Until here, a user interaction process ends. It can be seen throughout the process data flows are unidirectional, in this way ensuring a clear process.

2019-08-01-17-29-20
Redux principle Detailed

How to react-redux works?
Provider: Provider of action is the whole package from most external applications, and connect the module delivery store
connect: Redux and is responsible for connecting React
to obtain state: connect acquire Provider in store through context, through the store. getState () Gets all store tree state on the entire
package of the original components: the state and action manner props passed through the internal components of the original objects ReactComponent wrapWithConnect returns a Connect, Connect original re-render incoming external component WrappedComponent, and to connect the incoming mapStateToProps, on mapDispatchToProps with the component after the original props merge, pass through attribute WrappedComponent
monitor store tree change: connect caches store tree state in the state, by comparing the current state and the state before the state change state, thereby determine whether to call this.setState () method to trigger re-rendering Connect and its subcomponents
2019-08-01-22-21-51
difference redux of the mobx?
contrast between the two:

redux stored in a single data store in, mobx data stored in the store in the dispersed plurality
redux stored data object using Plain, requires manual operation of the process variations; mobx suitable observable save data, after the data processing operation in response to the automatic change
redux immutable state, which means that the status is read-only, not directly to modify it, but should return to a new state, while the use of pure function; state mobx is variable and can be modified directly
mobx is relatively simple, in which there are a lot of abstract, mobx more use of object-oriented programming thinking; redux would be more complicated, because the idea of functional programming which is not so easy to master, but need the help of a series of intermediate pieces to handle asynchronous and side effects
mobx there are more abstract and packaging, debugging would be more difficult, but the result is difficult to predict; but redux can be back in time to provide development tools, while its purely functional and less abstract, let debugging become more easily
scene Analysis:

Based on these differences, we simply have to analyze the two different usage scenarios.

mobx more suitable for complex applications without data: mobx difficult to debug, many states can not go back, in the face of high complexity applications, often powerless.

redux suitable for retrospective application needs: for example, a drawing board application, a spreadsheet application, often need to undo, redo operation, as redux immutable characteristic, natural support these operations.

mobx for fast track projects: mobx started simple, less boilerplate code, can greatly improve development efficiency.

Of course mobx and redux is not necessarily either-or relationship, you can also project redux used as a global state management, to use as a component of the local state with mobx Manager.

redux how to perform asynchronous operation?
Of course, we can be requested directly componentDidmount in without the aid redux.

But in a certain scale of the project, the above methods are difficult to manage asynchronous stream, usually we will help redux asynchronous processing of asynchronous middleware.

redux asynchronous workflow middleware In fact, many have, but the current mainstream asynchronous middleware only two redux-thunk, redux-saga, of course redux-observable may also be eligible for a place, whether it is the rest of the asynchronous middleware community activity or npm download the amount than the poor.

? pros and cons between asynchronous middleware redux
redux-thunk advantages:

Small size: redux-thunk implementations is very simple, less than 20 lines of code
simply use: redux-thunk without introducing additional paradigms like redux-saga or redux-observable, simple to use
redux-thunk defects:

Too much boilerplate Code: redux with itself, usually a request requires a lot of code, but many of them are repetitive nature of the
coupling severe: asynchronous operation redux of action coupled together, convenient management
functions weak: There are some commonly used in the actual development function needs its own encapsulation
redux-saga advantages:

Decoupling Asynchronous: Asynchronous operation is being transferred to a separate saga.js, the doping is no longer in action.js or component.js
action to get rid thunk function: Parameter dispatch is still a pure action (the FSA), rather than full of "black magic" thunk function
exception handling: benefit from the generator function of the saga implement the code error / request failure can be directly through the try / catch syntax directly capture processing
and powerful: redux-saga provides a lot of Saga helper and Effect created is used for the developer, the developer can be encapsulated or simply packaged without using
flexible: redux-saga Saga may be a plurality of serial / parallel combination, a very useful form of asynchronous flow
testability, various case of test solution, including mock task, like branch coverage
redux-saga defects:

Additional educational costs: redux-saga not only in the use of incomprehensible generator function, and dozens of API, learning costs far more than redux-thunk, the most important thing is that you learn the extra cost is only to serve the library, and different redux-observable, although redux-observable also learn extra cost but a set of ideas behind rxjs and
bulky: slightly larger size, nearly 2,000 lines of code, min version is about 25KB
functions surplus: in fact, difficult to use features such as concurrency control but we still need to introduce these codes
ts support unfriendly: yield not return TS type
redux-observable advantages:

The most powerful: Because of our proximity to rxjs this powerful reactive programming library, with rxjs operator, you can almost do anything you can think of asynchronous processing
back rxjs: Because of blessing rxjs, if you've learned rxjs , redux-observable learning cost is not high, and with the rxjs upgrade redux-observable will become more powerful
redux-observable defects:

Learning costs extraordinarily high: If you do not rxjs, you need to learn two additional complex library
community in general: downloads redux-observable only redux-saga 1/5, the community is also not active enough in this complex asynchronous workflow middleware level redux-saga is still in the leading position in
a detailed comparison on redux-saga with redux-observable visible this link

Guess you like

Origin blog.51cto.com/14516164/2438641