Fetch package
npm install whatwg-fetch --save // Adapt to other browsersnpm install es6-promise export const handleResponse = (response) => { if ( === 403 || === 401) { const oauthurl = ('locationUrl'); if (!_.isEmpty(oauthUrl)) { = oauthurl; return; } } if (!) { return getErrorMessage(response).then(errorMessage => apiError(, errorMessage)); } if (isJson(response)) { return (); } if (isText(response)) { return (); } return (); }; const httpRequest = { request: ({ method, headers, body, path, query, }) => { const options = {}; let url = path; if (method) { = method; } if (headers) { = {...,...headers}; } if (body) { = body; } if (query) { const params = (query) .map(k => `${k}=${query[k]}`) .join('&'); url = (`?${params}`); } return fetch(url, ({}, options, { credentials: 'same-origin' })).then(handleResponse); }, }; export default httpRequest;
react performance optimization solution
- Rewrite
shouldComponentUpdate
To avoid unnecessary dom operations - use
production
Version of - use
key
Come and helpReact
Identify the minimum change of all subcomponents in the list
What is React Context?
Context
A method of passing data through the component tree is provided, thus avoiding manual transmission at every levelprops
property.
What is JSX
JSX is a syntax extension of JavaScript syntax and has all the functions of JavaScript. JSX produces React "elements", you can encapsulate any JavaScript expression in curly braces and embed it into JSX. After compilation is complete, the JSX expression becomes a regular JavaScript object, which means you canif
Statements andfor
The loop uses JSX internally, assigns it to a variable, accepts it as an argument, and returns it from the function.
What is props
- The core idea of react is componentization, and the page is divided into many independent and reusable components
- A component is a function that can accept a parameter as an input value. This parameter is props, so props is to pass data into the internal component from the outside.
- Due to react's one-way data flow pattern, props are data passed from the parent component to the child component
Where should Ajax request be initiated in the React component
In React components, it should becomponentDidMount
Initiate a network request. This method is executed when the component is "mounted" (added to the DOM) for the first time, and only once during the life of the component. More importantly, you cannot guarantee that the Ajax request has been completed before the component is mounted, and if so, it means you will try to call setState on an unmounted component, which will not work. existcomponentDidMount
Initiating a network request will ensure that there is a component that can be updated.
react force refresh
() An infrequently used life cycle method, its function is to force refresh
The official website explains as follows
By default, the component will be re-rendered when the state or props of the component changes. If the render() method depends on other data, you can call forceUpdate() to force the component to re-render.
Calling forceUpdate() will cause the component to call the render() method, which will skip the component's shouldComponentUpdate(). However, its child components trigger normal lifecycle methods, including the shouldComponentUpdate() method. If the tag changes, React will still update only the DOM.
Usually you should avoid using forceUpdate() and try to use and in render().
shouldComponentUpdate in initialization and forceUpdate will not be executed
What are the benefits of using React Hooks?
First, Hooks generally support extracting and reusing stateful logic common across multiple components without the need to assume higher-order components or rendering.props
The burden.Hooks
The state of function components can be easily manipulated without the need to convert them into class components.
Hooks do not work in classes, by using them we can completely avoid using lifecycle methods, e.g.componentDidMount
、componentDidUpdate
、componentWillUnmount
. Instead, useuseEffect
Such a built-in hook.
Redux internal principle How to implement dispstch function internally
byredux-thunk
Middleware as an example, the following isthunkMiddleware
Function code
// Part of it is converted to ES5 code, and running the middleware function will return a new function, as follows:return ({ dispatch, getState }) => { // next is actually the dispatch passed in return function (next) { return function (action) { // redux-thunk core if (typeof action === 'function') { return action(dispatch, getState, extraArgument); } return next(action); }; }; }
redux-thunk
The source code inside the library is very simple and allowsaction
It is a function and supports parameter passing, otherwise the call method will not change
-
redux
createStore
:passcombineReducers
Function Mergereducer
function, return a new functioncombination
(This function is responsible for loop traversal operationreducer
Function, return allstate
). Pass this new function as a parametercreateStore
Function, the function is initialized and executed through dispatch.combination
, state generated, return store object -
redux
middleware:applyMiddleware
The main purpose of function middleware is to modifydispatch
Function, return a new processed by middlewaredispatch
function -
redux
Use: In fact, it is to call the loop traversal call againreducer
Function, updatestate
What is a pure function
A pure function is a function that does not depend on and does not change the state of a variable outside its scope, which also means that a pure function always returns the same result for the same parameters.
How to configure React-Router to implement routing switching
(1) Use<Route>
Components
Routing matches are through comparison<Route>
The path attribute and the pathname of the current address are implemented. When a<Route>
When the match is successful, it renders its contents and when it does not match, it renders null. No path<Route>
Will always be matched.
// when location = { pathname: '/about' } <Route path='/about' component={About}/> // renders <About/> <Route path='/contact' component={Contact}/> // renders null <Route component={Always}/> // renders <Always/>
(2) Use in combination<Switch>
Components and<Route>
Components
<Switch>
Used to<Route>
Group.
<Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/contact" component={Contact} /> </Switch>
<Switch>
Not grouping<Route>
It's necessary, but it's usually useful. one<Switch>
It will traverse all its subs<Route>
element, and render only the first element that matches the current address.
(3) Use<Link>、 <NavLink>、<Redirect>
Components
<Link>
Components to create links in your application. No matter where you render one<Link>
, the anchor will be rendered in the HTML of the application (<a>
)。
<Link to="/">Home</Link> // <a href='/'>Home</a>
is a special type when its to attribute matches the current address, it can be defined as "active".
// location = { pathname: '/react' } <NavLink to="/react" activeClassName="hurray"> React </NavLink> // <a href='/react' className='hurray'>React</a>
When we want to force navigation, we can render a<Redirect>
, when one<Redirect>
When rendering, it will use its to attribute for orientation.
In React, what is state
State is similar to props, but it is private and completely controlled by the component itself. State is essentially an object that holds data and determines how components render.
What are the reconciliation stages and commit stages of react16 versions?
- The main work included in the reconciliation stage is to do diff calculations for current tree and new tree to find out the changing parts. You can interrupt traversal, compare, etc., and wait for a while and then come again.
- The commit phase is to apply the changes obtained in the previous stage to the real DOM tree, and is a series of DOM operations. Not only should you maintain more complex DOM states, but you should continue after interruption, which will have an impact on the user experience. In common application scenarios, the time-consuming process of this stage is relatively shorter than that of diff calculations.
What is the difference between a class component and a function component?
- Class components can use other features such as states
state
and life cycle hook. - When the component just receives
props
When rendered to a page, it is a stateless component, which belongs to a function component, also known as a dumb component or a display component.
Of course, there is a difference between function components and class components, and the performance of function components is higher than that of class components, because class components need to be instantiated when used, and function components can directly execute the function to get the return result. To improve performance, try to use function components.
the difference | Function Components | Class Components |
---|---|---|
Is there anythis
|
No | have |
Is there a life cycle | No | have |
Is there status?state
|
No | have |
How to re-render the same component when routing changes?
When the route changes, that is, the component's props change, a life cycle hook such as componentWillReceiveProps will be called. All that needs to be done is: When the route changes, according to the route, also request data:
class NewsList extends Component { componentDidMount () { (); } fetchData(location) { const type = ('/', '') || 'top' (fetchListData(type)) } componentWillReceiveProps(nextProps) { if ( != ) { (); } } render () { ... } }
Use the life cycle componentWillReceiveProps to perform the re-released preprocessing operation.
react life cycle
Initialization phase:
- getDefaultProps: Get the default properties of the instance
- getInitialState: Get the initialization state of each instance
- componentWillMount: The component will be loaded and rendered to the page soon
- render: The component generates a virtual DOM node here
- componentDidMount: After the component is actually loaded
Running status:
- componentWillReceiveProps: Called when the component is about to receive the property
- shouldComponentUpdate: When the component accepts a new attribute or new state (it can return false, and it will not update after receiving the data, prevent the render call, and the subsequent functions will not be executed)
- componentWillUpdate: The component is about to be updated and cannot modify properties and status
- render: component re-deline
- componentDidUpdate: The component has been updated
Destruction phase:
- componentWillUnmount: The component is about to be destroyed
What does shouldComponentUpdate do, (which periodic function is react performance optimization?)
shouldComponentUpdate This method is used to determine whether the render method needs to be called to re-deline the dom. Because the description of dom is very performance-consuming, if we can write a more optimized dom diff algorithm in the shouldComponentUpdate method, it can greatly improve performance.
In react17, the following three life cycles will be deleted
componentWillMount,componentWillReceiveProps , componentWillUpdate
How does non-necked relational components communicate?
That is, there is no component that contains relationships, including sibling components and non-sibling components that are not in the same parent.
- Custom event communication can be used (publish subscription mode)
- Global state management can be performed through redux, etc.
- If it is a sibling component communication, you can find the common parent node of these two sibling nodes and communicate in combination with the communication method between the father and son.
What is a store in Redux
Store is a javascript object that saves the entire application's state. At the same time, Store also assumes the following responsibilities:
- Allowed to pass
getState()
Visit state - Run through
dispatch(action)
Change state - pass
subscribe(listener)
Register listeners - pass
subscribe(listener)
The returned function handles the logout of listeners
What problems did react solve and what added
React's three new features Time Slicing, Suspense, hooks
- Time Slicing (solves CPU speed problem) enables you to pause at any time during the execution of tasks and run to do other things. This feature allows react to maintain good performance when running machines with extremely poor performance.
- Suspense (solve network IO problems)Cooperate with lazy to realize asynchronous loading of components. It can pause the rendering of the current component, and continue to render after completing something, solve the problem of "asynchronous side effects" that have existed since react was born to the present, and it is not solved elegantly. It uses the T asynchronous but synchronous writing method. This is the best way to solve the asynchronous problem.
- Provides aBuilt-in function componentDidCatch, When an error occurs, the fallback component can be displayed friendly; exceptions thrown by its child elements (including nested child elements) can be caught; the error component can be reused.
(1) React16.8 adds hooks to make React functional components more flexible. Before hooks, React had many problems:
- It's hard to reuse state logic between components
- Complex components become difficult to understand, and the nesting of higher-order components and functional components is too deep.
- This pointing problem with class component
- An unmemorable life cycle
hooks solve the above problems very well, hooks provide many methods
- useState Returns a stateful value and a function that updates this stateful value
- useEffect accepts functions that contain imperative code that may have side effects.
- useContext accepts the context object (value returned from) and returns the current context value,
- useReducer Alternative to useState. Accepts a reducer of type (state, action) => newState and returns the current state paired with the dispatch method.
- useCalLback Returns a memoized version of the memory that will only change if one of the inputs changes. Input and output determinism of pure functions o useMemo Pure memory function o useRef Returns a mutable ref object whose Current property is initialized as a passed parameter, and the returned ref object remains unchanged throughout the entire life of the component.
- useImperativeMethods Customize the instance value exposed to the parent component when using ref
- useMutationEffect Before updating a sibling component, it triggers synchronously at the same stage when React performs its DOM change
- useLayoutEffect Synchronous trigger after DOM is changed. Use it to read the layout from the DOM and re-render synchronously
(2)React16.9
- Rename Unsafe's lifecycle method. The new UNSAFE_prefix will help make these problematic words more prominent during code review and debug
- Abandoned javascript: URL in form. URLs starting with javascript: are very vulnerable to attacks and cause security vulnerabilities.
- Deprecated "Factory" components. Factory components can cause React to grow larger and slower.
- act() also supports asynchronous functions, and you can use await when calling it.
- Use <> to perform performance evaluation. Tracking performance regression in larger applications can be convenient
(3)React16.13.0
- Supports calling setState during rendering, but only for the same component
- Style rules that detect conflicts and record warnings
- Deprecated unstable_createPortal, use CreatePortal
- Adding the component stack to its development warnings enables developers to isolate bugs and debug their programs, which clearly states the problem and locates and fixes errors faster.
What is React Fiber?
Fiber yes React 16 China New Coordination Engine may re-implement core algorithms。 Its main goal is to support incremental rendering of virtual DOM. React Fiber’s goal is to improve its applicability in animation, layout, gestures, pauses, aborts, or reuse, and assign priority to different types of updates, as well as new concurrency primitives.
React Fiber’s goal is to enhance its applicability in areas such as animation, layout and gestures. Its main feature is incremental rendering:Ability to split rendering work into chunks,and spread it into multiple frames。
This is the article about the collection of common react interview questions in front-end. For more related react interview questions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!