Front end internship interview preparation -- react others

Sourire 2021-09-15 09:05:20
end internship interview preparation react


React What is the recommended way to name components ?

Name components by reference rather than by displayName.

Use displayName Name the component :

export default React.createClass({ displayName: 'TodoApp', // ...})
 Copy code 

React Recommended method :

export default class TodoApp extends React.Component { // ...}
 Copy code 

react What's the problem with the latest version , What's added

React 16.x Three new features of Time Slicing、Suspense、 hooks

  • Time Slicing( solve CPU Speed problem ) So that it can be suspended at any time during the execution of the task , Run to something else , This feature makes react Can run on extremely poor machines , Still maintain good performance
  • Suspense ( Solve the network IO problem ) and lazy coordination , Implement asynchronous loading of components . Can pause the rendering of the current component , Continue rendering when you have finished something , Solve from react Born to the present 「 Asynchronous side effects 」 The problem of , And it's solved gracefully , It uses T Asynchronous but synchronous writing , This is the best way to solve the asynchronous problem
  • Provides a Built in functions componentDidCatch, When something goes wrong , Can show... In a friendly way fallback Components ; You can capture its child elements ( Including nested sub elements ) Exception thrown ; Error components can be reused .

(1)React16.8 Join in hooks, Give Way React Functional components are more flexible ,hooks Before ,React There are many problems :

  • It's hard to reuse state logic between components
  • Complex components become difficult to understand , The nesting of high-order components and function components is too deep .
  • class Component's this Point to the problem
  • The unforgettable life cycle

hooks Well solved the above problems ,hooks There are many ways

  • useState Returns a stateful value , And the function to update this state value
  • useEffect Accept include imperative , Functions that may have side effect code .
  • useContext Accept context objects ( from React.createContext The value returned ) And return the current context value ,
  • useReducer useState alternatives . The type of acceptance is (state,action)=> newState Of reducer, And back with dispatch The current state of method pairing .
  • useCalLback Back to a memory memoized edition , This version will only change if one of the inputs changes . The deterministic input-output function o useMemo A pure memory function o useRef Return to a variable ref object , Its Current Property is initialized as the passed parameter , Back to ref Objects remain the same throughout the life cycle of the component .
  • useImperativeMethods Custom use ref The instance value exposed to the parent component
  • useMutationEffect Before updating sibling components , It's in React To perform its DOM The same phase of the change is triggered synchronously
  • useLayoutEffect DOM Sync trigger after change . Use it to DOM Read layout and re render synchronously

(2)React16.9

  • rename Unsafe Life cycle approach to . new UNSAFE_ Prefixes will help in code review and debug period , Make these problematic words more prominent
  • abandoned javascrip: Formal URL. With javascript: At the beginning URL Very vulnerable to attack , Create security holes .
  • abandoned "Factory" Components . Factory components can cause React Bigger and slower .
  • act() Asynchronous functions are also supported , And you can use... When calling it await.
  • Use <React.ProfiLer> Perform performance evaluation . In larger applications, tracking performance regression may be convenient

(3)React16.13.0

  • Support calling during rendering setState, But only for the same component
  • Detects conflicting style rules and logs warnings
  • abandoned unstable_createPortal, Use CreatePortal
  • Add a component stack to its development warning , Enables developers to isolate bug And debug its program , This clearly illustrates the problem , And locate and fix errors faster .

react To achieve a global dialog

import React, { Component } from 'react';
import { is, fromJS } from 'immutable';
import ReactDOM from 'react-dom';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import './dialog.css';
let defaultState = {
  alertStatus:false,
  alertTip:" Tips ",
  closeDialog:function(){},
  childs:''
}
class Dialog extends Component{
  state = {
    ...defaultState
  };
  // css Set the animation component as the target component
  FirstChild = props => {
    const childrenArray = React.Children.toArray(props.children);
    return childrenArray[0] || null;
  }
  // Open the pop-up window
  open =(options)=>{
    options = options || {};
    options.alertStatus = true;
    var props = options.props || {};
    var childs = this.renderChildren(props,options.childrens) || '';
    console.log(childs);
    this.setState({
      ...defaultState,
      ...options,
      childs
    })
  }
  // Close the pop-up window
  close(){
    this.state.closeDialog();
    this.setState({
      ...defaultState
    })
  }
  renderChildren(props,childrens) {
    // Traverse all subcomponents
    var childs = [];
    childrens = childrens || [];
    var ps = {
        ...props,  // Bind subcomponents props
        _close:this.close  // Bind a pop-up window closing event to the sub component     
       };
    childrens.forEach((currentItem,index) => {
        childs.push(React.createElement(
            currentItem,
            {
                ...ps,
                key:index
            }
        ));
    })
    return childs;
  }
  shouldComponentUpdate(nextProps, nextState){
    return !is(fromJS(this.props), fromJS(nextProps)) || !is(fromJS(this.state), fromJS(nextState))
  }
   
  render(){
    return (
      <ReactCSSTransitionGroup
        component={this.FirstChild}
        transitionName='hide'
        transitionEnterTimeout={300}
        transitionLeaveTimeout={300}>
        <div className="dialog-con" style={this.state.alertStatus? {display:'block'}:{display:'none'}}>
            {this.state.childs}
        </div>
      </ReactCSSTransitionGroup>
    );
  }
}
let div = document.createElement('div');
let props = {
   
};
document.body.appendChild(div);
let Box = ReactD
Copy code
 Copy code 

Subclass :

// Subclass jsx
import React, { Component } from 'react';
class Child extends Component {
    constructor(props){
        super(props);
        this.state = {date: new Date()};
  }
  showValue=()=>{
    this.props.showValue && this.props.showValue()
  }
  render() {
    return (
      <div className="Child">
        <div className="content">
           Child
           <button onClick={this.showValue}> Call the parent method </button>
        </div>
      </div>
    );
  }
}
export default Child;
Copy code
 Copy code 

css:

.dialog-con{
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.3);
}
 Copy code 

React Is there any practice of data persistence ?

Encapsulate data persistence components :

let storage={
// increase
set(key, value){
localStorage.setItem(key, JSON.stringify(value));
},
// obtain
get(key){
return JSON.parse(localStorage.getItem(key));
},
// Delete
remove(key){
localStorage.removeItem(key);
}
};
export default Storage;
 Copy code 

stay React In the project , adopt redux When storing global data , There will be a problem , If the user refreshes the web page , Then through the redux The stored global data will be emptied , Such as login information . At this time, there will be a need for global data persistent storage . The first thing that comes to mind localStorage,localStorage There is no time limit for data storage , It can be used to realize the persistent storage of data .

But already in use redux To manage and store global data , Use it again localStorage To read and write data , This is not only a huge workload , It's easy to make mistakes . So there is no combination redux The framework to achieve the function of persistent data storage ? Of course , It is redux-persist.redux-persist Will redux Of store Cache the data in to the browser localStorage in . The steps are as follows :

(1) First install redux-persist:

npm i redux-persist
 Copy code 

(2) about reducer and action The treatment of remains the same , Only need to modify store Build code for , Revised as follows :

import {createStore} from 'redux'
import reducers from '../reducers/index'
import {persistStore, persistReducer} from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';
const persistConfig = {
key: 'root',
storage: storage,
stateReconciler: autoMergeLevel2 // see 'Merge Process' Some details
};
const myPersistReducer = persistReducer(persistConfig, reducers)
const store = createStore(myPersistReducer)
export const persistor = persistStore(store)
export default store
 Copy code 

(3) stay index.js in , take PersistGate Tag as the parent tag of web page content :

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux'
import store from './redux/store/store'
import {persistor} from './redux/store/store'
import {PersistGate} from 'redux-persist/lib/integration/react';
ReactDOM.render(<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
{/* Web content */}
</PersistGate>
</Provider>, document.getElementById('root'));
 Copy code 

This is done through redux-persist Realization React Simple application of persistent local data storage .

Yes React and Vue The understanding of the , Their similarities and differences

Similarity :

  • Keep your focus on the core library , Other functions, such as routing and global state management, are handed over to related libraries
  • They all have their own building tools , It allows you to get a project template set according to best practices .
  • It's all used Virtual DOM( fictitious DOM) Improve redraw performance
  • There are props The concept of , Allow data transfer between components
  • Encourage component application , Split the application into modules with clear functions , Improve reusability

The difference :

1) Data flow

Vue Data bidirectional binding is supported by default , and React One way data flow has always been advocated

2) fictitious DOM

Vue2.x Start introducing "Virtual DOM", Eliminates and React The difference in this respect , But in the specific details, they have their own characteristics .

  • Vue Claim to be able to calculate... Faster Virtual DOM The difference of , This is because it's in the rendering process , Will track the dependencies of each component , There is no need to re render the entire component tree .
  • about React for , Whenever the state of the application is changed , All subcomponents will be re rendered . Of course , This can be done by PureComponent/shouldComponentUpdate This life cycle approach to control , but Vue Think of this as the default optimization .

3) Componentization

React And Vue The biggest difference is the writing of templates .

  • Vue Encourage writing similar to routine HTML The template of . It's close to the standard HTML Elements , It's just a little bit more attributes .
  • React It is recommended that all your templates be common JavaScript Grammar extension of ——JSX Writing .

In particular :React in render Functions support closure features , So we import The components of are in render You can call . But in Vue in , Because the data used in the template must be hung in this Last transit , therefore import After completing the components , Still need to be in components Make a statement in .

4) The implementation principle of monitoring data change is different

  • Vue adopt getter/setter And hijacking some functions , Can accurately know the data changes , No special optimization is needed to achieve good performance
  • React The default is by comparing references , If not optimized (PureComponent/shouldComponentUpdate) May lead to a lot of unnecessary vDOM Re rendering of . This is because Vue Using variable data , and React More emphasis on the immutability of data .

5) High order component

react You can use higher-order components (Higher Order Components-- HOC) To expand , and vue Need to pass through mixins To expand .

The reason is that higher-order components are higher-order functions , and React The component itself is a pure function , So the higher-order function pair React It's easy to say . contrary Vue.js Use HTML Create a view component from a template , At this time, the template cannot be compiled effectively , therefore Vue Do not use HOC To achieve .

6) Building tools

Both have their own build tools

  • React ==> Create React APP
  • Vue ==> vue-cli

7) Cross platform

  • React ==> React Native
  • Vue ==> Weex

have access to TypeScript Write React Application ? How to operate ?

(1) If not already created Create React App project

  • Directly create one with typescript Of Create React App project :
 npx create-react-app demo --typescript
 Copy code 

(2) If you have already created  Create React App project , Need to put  typescript Introduce into existing projects

  • By order will typescript Introduce projects :
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
 Copy code 
  • Any in the project Suffix named ‘.js’ Of JavaScript Rename file to TypeScript The file suffix is ‘.tsx’( for example  src/index.js  Rename it to  src/index.tsx )

React Design thinking , What's the idea of it ?

(1) Write simple and intuitive code

React The biggest value is not high-performance virtual DOM、 Encapsulated event mechanism 、 Server-side rendering , But declarative and intuitive coding .react The first article in the document is declarative ,React Make creation interactive UI Make it easy . Design a concise view for each state of the application , When data changes React Can effectively update and render components correctly . Written in a declarative way UI, Can make the code more reliable , And easy to debug .

(2) Simplify reusable components

React A simplified component model is used in the framework , But the concept of componentization is used more thoroughly .React Will the whole UI Each functional module on the is defined as a component , Then small components are combined or nested to form larger components .React The components of have the following characteristics ∶

  • Can be combined : Simple components can be combined into complex components
  • reusable : Each component is independent , Can be used by multiple components
  • Maintainable : Component related logic and UI Are encapsulated inside the component , Convenient maintenance
  • Testable : Because of the independence of components , Testing components becomes much easier .

(3) Virtual DOM

The real page corresponds to a DOM Trees . In the traditional page development mode , Every time you need to update the page , It's all manual DOM To update . DOM It's very expensive to operate . In front end development , The biggest consumption of performance is DOM operation , And this part of the code will make the code of the whole project difficult To maintain .React Put the truth DOM The tree is transformed into JavaScript Object tree , That is to say Virtual DOM, After every data update , Recalculate Virtual DOM, And with the last generation Virtual DOM comparing , Batch update the changed parts .React It also provides an intuitive shouldComponentUpdate Lifecycle Callback , To reduce unnecessary after data changes Virtual DOM The comparison process , To guarantee performance .

(4) Functional programming

React Build the past over and over again UI The process is abstracted into components , And under the condition of given parameters, the corresponding UI Interface .React Can make full use of many functional methods to reduce redundant code . Besides , Because it is a simple function , So it's easy to test .

(5) A study , Write anywhere

No matter what technology stack is being used now , Can be introduced at any time React To develop new features , Without having to rewrite the existing code .

React You can also use Node Server rendering , Or use React Native Develop native mobile applications . because React Components can be mapped to corresponding native controls . At the time of output , It's output Web DOM, still Android Control , still iOS Control , It's up to the platform itself . therefore ,react It's easy to integrate with other platforms

React in props.children and React.Children The difference between

stay React in , When it comes to component nesting , Use... In the parent component props.children Show all the sub components . as follows :

function ParentComponent(props){
return (
<div>
{props.children}
</div>
)
}
 Copy code 

If you want to pass the properties in the parent component to all child components , Need to use React.Children Method .

such as , How many Radio combined , Synthesis of a RadioGroup, This requires all Radio Have the same name Property value . It can be like this : hold Radio As sub components ,RadioGroup As a parent component ,name Property value of RadioGroup Set... In this parent component .

The first is the sub component :

// Child components
function RadioOption(props) {
return (
<label>
<input type="radio" value={props.value} name={props.name} />
{props.label}
</label>
)
}
 Copy code 

Then the parent component , Not only do you need to show all its sub components , You also need to assign... To each sub component name Attributes and values :

// The parent component uses ,props Refers to the parent component props
function renderChildren(props) {
// Traverse all subcomponents
return React.Children.map(props.children, child => {
if (child.type === RadioOption)
return React.cloneElement(child, {
// Put the parent component's props.name Assigned to each sub component
name: props.name
})
else
return child
})
}
// Parent component
function RadioGroup(props) {
return (
<div>
{renderChildren(props)}
</div>
)
}
function App() {
return (
<RadioGroup name="hello">
<RadioOption label=" Option one " value="1" />
<RadioOption label=" Option 2 " value="2" />
<RadioOption label=" Option 3 " value="3" />
</RadioGroup>
)
}
export default App;
 Copy code 

above ,React.Children.map Let's have more flexible control over all child components of the parent component

React What is the state of ascension ? What are the use scenarios ?

React The state promotion of is the user's operation on sub components , Subcomponents do not change their state , Through your own props Pass the data changed by this operation to the parent component , Change the state of the parent component , This changes the state of all child components controlled by the parent component , This is also React The characteristics of a single data stream determine . The official saying is : share state( state ) This is achieved by moving it to the nearest common ancestor component of the component that needs it . This is known as “ Status up (Lifting State Up)”.

Generally speaking, it is Promote the state that multiple components need to share to their nearest parent component , Change this state on the parent component and pass props Distribute to subcomponents .

A simple example , There are two in the parent component input Child components , If you want to enter data in the first input box , To change the value of the second input box , This requires state improvement .

class Father extends React.Component {
constructor(props) {
super(props)
this.state = {
Value1: '',
Value2: ''
}
}
value1Change(aa) {
this.setState({
Value1: aa
})
}
value2Change(bb) {
this.setState({
Value2: bb
})
}
render() {
return (
<div style={{ padding: "100px" }}>
<Child1 value1={this.state.Value1} onvalue1Change={this.value1Change.bind(this)} />
<Child2 value2={this.state.Value1} />
</div>
)
}
}
class Child1 extends React.Component {
constructor(props) {
super(props)
}
changeValue(e) {
this.props.onvalue1Change(e.target.value)
}
render() {
return (
<input value={this.props.Value1} onChange={this.changeValue.bind(this)} />
)
}
}
class Child2 extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<input value={this.props.value2} />
)
}
}
ReactDOM.render(
<Father />,
document.getElementById('root')
)
 Copy code 

React in constructor and getInitialState The difference between ?

Both are used to initialize state Of . The former is ES6 Chinese grammar , The latter is ES5 Chinese grammar , The new version of the React This method has been abandoned in .

getInitialState yes ES5 The method in , If you use createClass Method to create a Component Components , It can be called automatically getInitialState Method to get the initialized State object ,

var APP = React.creatClass ({
getInitialState() {
return {
userName: 'hi',
userId: 0
};
}
})
 Copy code 

React stay ES6 Removed from the implementation of getInitialState This hook function , Regulations state stay constructor To realize , as follows :

Class App extends React.Component{
constructor(props){
super(props);
this.state={};
}
}
 Copy code 

React How to use the strict mode , What's the use ?

StrictMode Is a tool for highlighting potential problems in an application . And Fragment equally ,StrictMode Doesn't render anything visible UI. It triggers additional checks and warnings for its descendants . Strict mode can be enabled for any part of the application . for example :

import React from 'react';
function ExampleApplication() {
return (
<div>
<Header />
<React.StrictMode>
<div>
<ComponentOne />
<ComponentTwo />
</div>
</React.StrictMode>
<Footer />
</div>
);
}
 Copy code 

In the example above , It won't be right Header and Footer Component operation strict mode check . however ,ComponentOne and ComponentTwo And all their descendant elements will be checked .

StrictMode At present, it helps :

  • Identify unsafe life cycles
  • About using obsolete strings ref API Warning of
  • About the use of waste findDOMNode Method warning
  • Detect unexpected side effects
  • Detect out of date context API

stay React What are the traversal methods in ?

(1) Traversal array :map && forEach

import React from 'react';
class App extends React.Component {
render() {
let arr = ['a', 'b', 'c', 'd'];
return (
<ul>
{
arr.map((item, index) => {
return <li key={index}>{item}</li>
})
}
</ul>
)
}
}
class App extends React.Component {
render() {
let arr = ['a', 'b', 'c', 'd'];
return (
<ul>
{
arr.forEach((item, index) => {
return <li key={index}>{item}</li>
})
}
</ul>
)
}
}
 Copy code 

(2) Traversing objects :map && for in

class App extends React.Component {
render() {
let obj = {
a: 1,
b: 2,
c: 3
}
return (
<ul>
{
(() => {
let domArr = [];
for(const key in obj) {
if(obj.hasOwnProperty(key)) {
const value = obj[key]
domArr.push(<li key={key}>{value}</li>)
}
}
return domArr;
})()
}
</ul>
)
}
}
// Object.entries() Convert objects into arrays
class App extends React.Component {
render() {
let obj = {
a: 1,
b: 2,
c: 3
}
return (
<ul>
{
Object.entries(obj).map(([key, value], index) => { // item Is an array , hold item deconstruction , It's written in [key, value]
return <li key={key}>{value}</li>
})
}
</ul>
)
}
}
 Copy code 

stay React How to retain data when a page is reloaded in ?

This problem is designed to Data persistence , The main implementation methods are as follows :

  • Redux: Store the data of the page in redux in , When reloading the page , obtain Redux Data in ;
  • data.js: Use webpack Projects built , You can create a file ,data.js, Save the data data.js in , Jump to the page and get ;
  • sessionStorge: Before entering the select address page ,componentWillUnMount When , Store data to sessionStorage in , Each time you enter the page, judge sessionStorage Is there a stored value in , Yes , Then read the rendering data ; No, , It indicates that the data is in the initialization state . Return to or enter a page other than the selected address , Clear the stored sessionStorage, Ensure that the next entry is initialized data
  • history API: History API Of pushState The function can associate an arbitrary serializable with a history state, So you can route push Save some information of the current page to state in , The next time you return to this page, you can start from state Take out the data before leaving and re render .react-router Can directly support . This method is suitable for some scenarios that need temporary storage .

Reference these three libraries at the same time react.js、react-dom.js and babel.js What do they all do ?

  • react: contain react The necessary core code
  • react-dom:react Rendering the core code required on different platforms
  • babel: take jsx convert to React Code tools

React You have to use JSX Do you ?

React The use of... Is not mandatory JSX. When you don't want to configure in the build environment JSX Compile time , be not in React Use in JSX It will be more convenient .

Every JSX Element just calls React.createElement(component, props, ...children) The grammar sugar of . therefore , Use JSX Anything that can be done can be done through pure JavaScript complete .

for example , use JSX Code written :

class Hello extends React.Component {
render() {
return <div>Hello {this.props.toWhat}</div>;
}
}
ReactDOM.render(
<Hello toWhat="World" />,
document.getElementById('root')
);
 Copy code 

Can be written without JSX Code for :

class Hello extends React.Component {
render() {
return React.createElement('div', null, `Hello ${this.props.toWhat}`);
}
}
ReactDOM.render(
React.createElement(Hello, {toWhat: 'World'}, null),
document.getElementById('root')
);
 Copy code 

Why use jsx You don't see the use of react But we need to introduce react?

In essence JSX yes React.createElement(component, props, ...children) Method of grammar sugar . stay React 17 Before , If used JSX, It's actually using React, babel  Will convert the component to  CreateElement  form . stay React 17 after , There is no need to introduce , because  babel  Can already help us automatically introduce react

stay React How to use async/await?

async/await yes ES7 New features in the standard . If using React Official scaffold creation project , You can use it directly . If it's self built webpack Used in configured projects , May come across  regeneratorRuntime is not defined  An unexpected error of . Then we need to introduce babel, And in babel Configured in async/await. You can use babel Of transform-async-to-module-method Plug in to convert it into browser supported Syntax , Although there is no performance improvement , But the coding experience is better .

React.Children.map and js Of map What's the difference? ?

JavaScript Medium map Not for null perhaps undefined Data processing , and React.Children.map Medium map Can handle React.Children by null perhaps undefined The situation of .

Yes React SSR The understanding of the

Server side rendering is composed of data and templates html, namely HTML = data + Template . Generate components or pages through the server html character string , And send it to the browser , Finally, we will mark it statically " blend " For fully interactive applications on the client side . The page is not rendered with a service , When requesting a page , Back to body Inside is empty , After performing js take html Structure injection into body in , combination css Show it ;

SSR The advantages of :

  • Yes SEO friendly
  • All templates 、 Images and other resources exist on the server side
  • One html Return all data
  • Reduce HTTP request
  • Fast response 、 Good user experience 、 Fast rendering of the first screen

1) More favorable SEO

Different reptiles work in the same way , Only crawling source code , Will not execute any scripts for the website, using React Or other MVVM After the framework , Most pages DOM The elements are on the client side js Dynamic generation , The content available for crawler capture and analysis is greatly reduced . in addition , Browser crawlers don't wait for our data to complete before grabbing page data . What the server render returns to the client is that the asynchronous data has been obtained and executed JavaScript The end of the script HTML, You can grab the information of the complete page in the network crawl .

2) Better for the first screen rendering

The rendering of the first screen is node Sent by html character string , It doesn't depend on js The file , This will allow users to see the content of the page faster . Especially for large single page applications , After packing, the file volume is relatively large , Normal client rendering takes a long time to load all files , The home page will have a long white screen waiting time .

SSR Limitations :

1) The server is under a lot of pressure

It was originally done through the client , Now unified to the server node Service to do . Especially in the case of high concurrent access , It will occupy a large number of servers CPU resources ;

2) Development conditions are limited

In server rendering , Only until componentDidMount Previous life cycle hooks , Therefore, third-party libraries referenced by the project cannot use other life cycle hooks , This limits the choice of reference libraries ;

3) The cost of learning is relatively high

Except yes webpack、MVVM Be familiar with the framework , You still need to master node、 Koa2 And other related technologies . Relative to client rendering , The project build 、 The deployment process is more complex .

Time consuming :

1) Data request

The server requests the first screen data , Instead of the client requesting first screen data , This is a " fast " One of the main reasons . The server makes a request on the intranet , Fast data response . The client makes data requests in different network environments , And Extranet http High request overhead , Lead to time difference

  • Client data request

51612599334_.pic.jpg

  • Server data request

61612599340_.pic.jpg

2)html Rendering

Server side rendering is to request data from the back-end server first , Then generate the full first screen html Back to the browser ; And client-side rendering is waiting js The code download 、 load 、 Request data rendering after parsing , The waiting process page has nothing , Is the white screen seen by the user . That is, server-side rendering does not need to wait js Code download complete and request data , You can return to the first screen page with complete data .

  • Not ssr html Rendering

31612599269_.pic.jpg

  • ssr html Rendering

41612599275_.pic.jpg

Why?  React Use JSX?

JSX It's a JavaScript Grammar extension of , Or something like XML Of ECMAScript Grammar extension . It doesn't have many grammatical definitions , Nor do we expect to introduce more standards .

Actually React It is not mandatory to use JSX. In the absence of JSX When ,React Implementing a component depends on using React.createElement function . The code is as follows :

class Hello extends React.Component {
render() {
return React.createElement(
'div',
null,
`Hello ${this.props.toWhat}`
);
}
}
ReactDOM.render(
React.createElement(Hello, {toWhat: 'World'}, null),
document.getElementById('root')
);
 Copy code 

and JSX More like a grammar sugar , Through something like XML How to describe , Describe function objects . When using JSX after , This code will be written like this :

class Hello extends React.Component {
render() {
return <div>Hello {this.props.toWhat}</div>;
}
}
ReactDOM.render(
<Hello toWhat="World" />,
document.getElementById('root')
);
 Copy code 

by force of contrast , It is clear that , The code becomes more concise , And the code structure level is clearer .

because React You need to convert components into virtual DOM Trees , So when writing code , It's actually writing a structural tree . and XML In the description of tree structure, it has the advantage of strong readability .

But such readable code is only for students who write programs , In fact, when running , Will use Babel The plug-in will JSX The syntax code is restored to React.createElement Code for .

summary : JSX It's a JavaScript Grammar extension of , The structure is similar to XML.JSX Mainly used to declare React Elements , but React The use of... Is not mandatory in JSX. Even if JSX, Also during the construction process , adopt Babel The plug-in is compiled as React.createElement. therefore JSX More like React.createElement A kind of grammar sugar .

React The team doesn't want to introduce JavaScript Development system other than itself . Instead, we hope to maintain the purity of component development through reasonable separation of concerns

HOC comparison mixins What are the advantages ?

HOC and Vue Medium mixins The effect is consistent , And in the early days React Is also used mixins The way . But in use class After creating the component in the same way ,mixins It can't be used , And actually mixins There are also some problems , such as :

  • It implies some dependency , For example, I wrote something in the component state And in mixin Used in , There's a dependency here . In case someone else wants to remove it next time , I have to go mixin Find dependencies in
  • Multiple mixin There may be functions with the same name in , At the same time, functions with the same name cannot appear in code components , Otherwise it's rewriting , In fact, I always think that naming is really a troublesome thing ..
  • Snowball effect , Although I still use the same component mixin, But one mixin Will be used by multiple components , There may be a need for mixin Modify the original function or add more functions , This may create a maintenance cost

HOC These problems were solved , And they have the same effect , It's also more politically correct ( After all, it's more functional )

React What design patterns are used for high-order components in ?

Used decoration mode , Application of high-order components :

function withWindowWidth(BaseComponent) {
class DerivedClass extends React.Component {
state = {
windowWidth: window.innerWidth,
}
onResize = () => {
this.setState({
windowWidth: window.innerWidth,
})
}
componentDidMount() {
window.addEventListener('resize', this.onResize)
}
componentWillUnmount() {
window.removeEventListener('resize', this.onResize);
}
render() {
return <BaseComponent {...this.props} {...this.state}/>
}
}
return DerivedClass;
}
const MyComponent = (props) => {
return <div>Window width is: {props.windowWidth}</div>
};
export default withWindowWidth(MyComponent);
 Copy code 

The decorative pattern is characterized by no need to change Decorated object In itself , But just put a shell interface on the outside .JavaScript There are already proposals for native decorators , Its usage is as follows :

@testable
class MyTestableClass {
}
 Copy code 
版权声明
本文为[Sourire]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/09/20210909142454922Z.html

  1. Contrôle de l'arbre en vue converti en style de table
  2. CSS3 animation flash Effect
  3. Discuter des propriétés de la file d'attente pour l'événement bloc
  4. Node around USModules
  5. Webpack - - Premier aperçu (concept de base)
  6. Mise en œuvre du cadre de base mvvm par JS natif
  7. Calculer les propriétés par rapport aux auditeurs, etc.
  8. Configuration standard dockerfile et docker-composer.yml
  9. Collection de questions d'entrevue HTML
  10. Conteneur, définir la largeur et la hauteur ne répond pas?
  11. Introduction et syntaxe des objets (mise à jour à long terme)
  12. Bubble Mart invests in cat galaxy, which is a vertical e-commerce platform around the quadratic element
  13. Exigences et dépendances dans package-lock.json
  14. Mouvement tridimensionnel de la terre, du ciel et de la lune basé sur three.js
  15. Compréhension et analyse de l'objet de base JS
  16. Simple use of status data management (context, mobx, Redux)
  17. Simulated drumming
  18. Array method
  19. Performance optimization issue 03 - HTTP request optimization
  20. Vue learning -- watch listener
  21. Learn more about nexttick in Vue
  22. Talk about some moves used by vue3.0 in the project - External skill chapter (I)
  23. JavaScript genrator generator
  24. La dernière réponse à l'entrevue de développement Android, l'hiver froid de l'industrie
  25. Maserati's motorcycle has less than 10 in the world. It is definitely a work of art
  26. 2021 partage des questions du dernier examen écrit d'entrevue Android, pas d'accord
  27. Programmation asynchrone Java scirp, développement frontal de base
  28. 2021 dernier examen écrit d'entrevue Android, écrit trop bien
  29. Quels aspects doivent être pris en considération dans le tableau principal du distributeur libre - service?
  30. He inherited his mother's hundreds of millions of property for his boyfriend to squander. Unexpectedly, he was ruthlessly abandoned when he had 100 yuan left
  31. The fuel cost is half less than that of fuel vehicles at the same level. Is it really cheap to use song Pro DM?
  32. Le dernier résumé de l'expérience d'entrevue d'embauche de l'école Android de l'usine est nécessaire pour l'usine
  33. Le dernier dictionnaire avancé de programmeurs d'usine, l'expérience d'entrevue d'embauche de l'Agence de développement Android
  34. La dernière collection d'entrevues Android Golden nine Silver ten
  35. L'expérience d'entrevue de l'Ingénieur d'algorithme de saut d'octets, 2 mois d'entrevue Tencent, station B, Netease et ainsi de suite sur 11 entreprises résumé!
  36. La dernière collection d'entrevues d'Android Golden nine Silver ten recommande un projet github
  37. Yuan Li's recent situation revealed that he was obsessed with public welfare, dressed simply and fearless, grew fat, and married an 11-year-old husband
  38. Initial experience of template tool plop of [front end Engineering]
  39. Dernière question d'entrevue avancée et réponse d'Alibaba Android, Alibaba P8 vous apprendra en personne
  40. Partage des dernières questions d'entrevue pour Android haute fréquence, Introduction aux compétences d'entrevue pour le développement d'Android
  41. Partager les dernières questions d'entrevue Android haute fréquence avec quelques conseils
  42. About JavaScript modules
  43. Iteratable object and class arrays
  44. Function realization of Vue elementui exporting excel form
  45. Use canvas to realize a small screenshot function
  46. Object oriented programming (2)
  47. Several common value transfer methods between Vue components
  48. Démarrer avec le serveur de base zéro: Hello World
  49. J'a I construit un escalier pour aller sur la lune, combien de façons puis - je poursuivre la sœur Chang'e?
  50. CSS implémente la fonction d'expansion et d'arrimage du Texte multiligne
  51. Varlet CLI | vue3 Component Library Quick Prototyping Tool
  52. Belle vue sur les trois rivières Xiapu
  53. La partie Web qui déploie SharePoint ajoute son propre module de fonctionnalité
  54. React Native (mise à jour à long terme)
  55. La conception et le codage de l'arbre binaire requis pour chaque entrevue d'embauche de la société Java millet;
  56. 10 jours pour obtenir l'offre d'emploi Android d'Alibaba, entrevue Android
  57. A remporté avec succès Byte, Tencent, Pulse offer, 7 ans Java une expérience d'entrevue de baise,
  58. 10大前端常用算法,web应用与开发
  59. Nginx - minimum configuration! You deserve it
  60. Les questions d'entrevue couramment utilisées pour le cadre Java sont - elles prometteuses pour le développement Java?