


What questions will be asked during the react interview? Detailed analysis and answers to common react interview questions
This article mainly introduces the analysis of common problems in react. There are questions and answers. Click here to see if one of the questions can help you solve your doubts. Let us read this article now
1. What is the difference between Element and Component in React?
The official website document explains Element as:
Elements are the smallest building blocks of React apps. An element describes what you want to see on the screen:
The official website explains Compent as:
Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen.
In other words, React Element describes what is seen on the screen. The data structure of the content is the object representation of the UI. A typical React Element is a declarative code piece built using JSX and then converted into a combination of createElement calls. React Component is a function or class that can receive parameter input and return a React Element.
2. JSX
React uses JSX to replace regular JavaScript. JSX is a JavaScript syntax extension that looks a lot like XML. We don't necessarily need to use JSX, but it has the following advantages:
JSX 执行更快,因为它在编译为 JavaScript 代码后进行了优化。 它是类型安全的,在编译过程中就能发现错误。 使用 JSX 编写模板更加简单快速。
3. What happens after calling setState?
After calling the setState function in the code, React will merge the passed parameter object with the current state of the component, and then trigger the so-called reconciliation process (Reconciliation). After the reconciliation process, React will build the React element tree based on the new state in a relatively efficient way and proceed to re-render the entire UI interface. After React obtains the element tree, React will automatically calculate the node difference between the new tree and the old tree, and then minimize and re-render the interface based on the difference. In the difference calculation algorithm, React can relatively accurately know which positions have changed and how they should be changed, which guarantees on-demand updates instead of full re-rendering.
4. Under what circumstances would you prefer to use Class Component instead of Functional Component?
Use Class Component when the component needs to contain internal state or use life cycle functions, otherwise use functional components.
5. At which step in the life cycle should you initiate an AJAX request?
We should put the AJAX request in the componentDidMount function for the following reasons:
React's next-generation reconciliation algorithm Fiber will optimize application performance by starting or stopping rendering. It will affect the number of triggers of componentWillMount. The number of calls to the componentWillMount lifecycle function becomes uncertain, and React may call componentWillMount multiple times and frequently. If we put the AJAX request in the componentWillMount function, then it will obviously be triggered multiple times, which is naturally not a good choice.
If we place the AJAX request in other functions of the life cycle, we cannot guarantee that the request will only require a response after the component is mounted. If our data request is completed before the component is mounted, and the setState function is called to add data to the component state, an error will be reported for the unmounted component. Making AJAX requests in the componentDidMount function can effectively avoid this problem. (If you want to learn more, go to the PHP Chinese website React Reference Manual column to learn)
6. What is the difference between Controlled Component and Uncontrolled Component?
One of the core components of React is autonomous components that can maintain internal state. However, when we introduce native HTML form elements (input, select, textarea, etc.), should we put all the data Host it into a React component or keep it in a DOM element? The answer to this question is the definitional separation of controlled and uncontrolled components. Controlled Component refers to components that are controlled by React and all form data is stored uniformly. In other words, if the value values of elements such as <input>, <textarea></textarea>, <select></select>
in React.js are controlled by React.js, then It is a controlled component. For example, in the following code, the username variable value is not stored in the DOM element, but is stored in the component status data. Any time we need to change the value of the username variable, we should call the setState function to modify it.
class ControlledForm extends Component { state = { username: '' } updateUsername = (e) => { this.setState({ username: e.target.value, }) } handleSubmit = () => {} render () { return ( <form onSubmit={this.handleSubmit}> <input type='text' value={this.state.username} onChange={this.updateUsername} /> <button type='submit'>Submit</button> </form> ) } }
Uncontrolled Component stores form data in the DOM, not in the React component. We can use refs to manipulate DOM elements:
class UnControlledForm extends Component { handleSubmit = () => { console.log("Input Value: ", this.input.value) } render () { return ( <form onSubmit={this.handleSubmit}> <input type='text' ref={(input) => this.input = input} /> <button type='submit'>Submit</button> </form> ) } }
Unexpectedly, uncontrolled components look better to implement. We can grab data directly from the DOM without adding additional code. However, we do not advocate the use of uncontrolled components in actual development, because in actual situations we need to consider more functional support such as form validation, selectively turning on or off button clicks, and forced input formats. At this time, we will host the data Into React helps us better complete these functions in a declarative manner. The original reason for introducing React or other MVVM frameworks is to free us from the heavy direct manipulation of the DOM.
7. What is the function of shouldComponentUpdate and why is it so important?
shouldComponentUpdate 允许我们手动地判断是否要进行组件更新,根据组件的应用场景设置函数的合理返回值能够帮我们避免不必要的更新。
8、概述下 React 中的事件处理逻辑
为了解决跨浏览器兼容性问题,React 会将浏览器原生事件(Browser Native Event)封装为合成事件(SyntheticEvent)传入设置的事件处理器中。这里的合成事件提供了与原生事件相同的接口,不过它们屏蔽了底层浏览器的细节差异,保证了行为的一致性。另外有意思的是,React 并没有直接将事件附着到子元素上,而是以单一事件监听器的方式将所有的事件发送到顶层进行处理。这样 React 在更新 DOM 的时候就不需要考虑如何去处理附着在 DOM 上的事件监听器,最终达到优化性能的目的。
9、传入 setState 函数的第二个参数的作用是什么?
该函数会在setState函数调用完成并且组件开始重渲染的时候被调用,我们可以用该函数来监听渲染是否完成:
this.setState( { username: 'tylermcginnis33' }, () => console.log('setState has finished and the component has re-rendered.') )
10、组件的生命周期
组件的生命周期分成三个状态:
Mounting:已插入真实 DOM Updating:正在被重新渲染 Unmounting:已移出真实 DOM
React 为每个状态都提供了两种处理函数,will 函数在进入状态之前调用,did 函数在进入状态之后调用,三种状态共计五种处理函数。
componentWillMount()componentDidMount()componentWillUpdate(object nextProps, object nextState)componentDidUpdate(object prevProps, object prevState)componentWillUnmount()
此外,React 还提供两种特殊状态的处理函数。
componentWillReceiveProps(object nextProps):已加载组件收到新的参数时调用shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时调用
本篇文章到这就结束了(想看更多就到PHP中文网React使用手册栏目中学习),有问题的可以在下方留言提问。
The above is the detailed content of What questions will be asked during the react interview? Detailed analysis and answers to common react interview questions. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools