Home > Web Front-end > JS Tutorial > body text

35 interview questions you must know and master React

青灯夜游
Release: 2020-09-02 15:33:56
forward
21148 people have browsed it

35 interview questions you must know and master React

[Related topic recommendations: react interview questions (2020)]

Question 1: What is Virtual DOM?

Theme: React
Difficulty: ⭐

Virtual DOM (VDOM) is an in-memory representation of the real DOM. The representation of the UI is kept in memory and synchronized with the actual DOM. This is a step that occurs between the rendering function being called and the element being displayed on the screen. The entire process is called reconciliation.

Question 2: What is the difference between class components and function components?

Theme: React
Difficulty: ⭐⭐
  • ##Class componentCan use other features such as statestate and lifecycle hooks.
  • When a component only receives
  • props and renders it to the page, it is a stateless component and is a functional component. It is also called 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, while function components directly execute function fetching Just return the result. To improve performance, try to use functional components.

DifferenceFunction componentClass component Is there NoYesIs there a life cycleNoYes##Is there a statestate

Question 3: Why are refs used in React?

Theme: React
Difficulty: ⭐⭐

Refs Provides a way to access the DOM created in the render method Methods of nodes or React elements. In a typical data flow, props is the only way for parent and child components to interact. If you want to modify a child component, you need to re-render it with a new pros. There are exceptions to everything. In some cases, we need to force modification of children outside of the typical data flow. In this case, Refs can be used.

We can add a ref attribute to the component to use. The value of this attribute is a callback function that receives the underlying DOM element or the mounted instance of the component as its first parameter.

class UnControlledForm extends Component {
  handleSubmit = () => {
    console.log("Input Value: ", this.input.value)
  }
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type=&#39;text&#39;
          ref={(input) => this.input = input} />
        <button type=&#39;submit&#39;>Submit</button>
      </form>
    )
  }
}
Copy after login

Please note that the input element has a ref attribute whose value is a function. This function receives the actual DOM element of the input and then places it on the instance so that it can be accessed inside the handleSubmit function.

It is often misunderstood that refs can only be used within class components, but refs can also be used with function components by leveraging closures in JS.

function CustomForm ({handleSubmit}) {
  let inputElement
  return (
    <form onSubmit={() => handleSubmit(inputElement.value)}>
      <input
        type=&#39;text&#39;
        ref={(input) => inputElement = input} />
      <button type=&#39;submit&#39;>Submit</button>
    </form>
  )
}
Copy after login

Question 4: How to handle events in React

Topic: React
Difficulty: ⭐⭐

In order to solve cross-browser issues Compatibility issue, SyntheticEvent instance will be passed to your event handler function, SyntheticEvent is React's cross-browser browser native event wrapper, it also has browser native events The same interface, including stopPropagation() and preventDefault().

What’s interesting is that React doesn’t actually attach events to the child nodes themselves. React uses a single event listener to listen to all events at the top level. This is good for performance and means React doesn't need to track event listeners when updating the DOM.

Question 5: What is the difference between state and props?

Theme: React
Difficulty: ⭐⭐

props and state are ordinary JS objects. Although they both contain information that affects rendered output, their functionality in terms of components is different. That is,

  • state is the component’s own data management, control of its own state, and is variable;
  • props is the data passed in from the outside. Parameters, immutable;
  • Those without state are called stateless components, and those with state are called stateful components;
  • Use props more , use less state, that is, write more stateless components.

Question 6: How to create refs

Theme: React
Difficulty: ⭐⭐

Refs are created using React .createRef() Created and attached to the React element via the ref attribute. When constructing a component, you typically assign Refs to instance properties so that they can be referenced throughout the component.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <p ref={this.myRef} />;
  }
}
Copy after login

Or use it like this:

class UserForm extends Component {
  handleSubmit = () => {
    console.log("Input Value is: ", this.input.value)
  }
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type=&#39;text&#39;
          ref={(input) => this.input = input} /> // Access DOM input in handle submit
        <button type=&#39;submit&#39;>Submit</button>
      </form>
    )
  }
}
Copy after login

Question 7: What are higher-order components?

Theme: React
Difficulty: ⭐⭐

Higher Order Component (HOC) is a function that accepts a component and returns a new component. Basically, this is a pattern derived from the composition feature of React, called Pure Components because they can accept any dynamically provided subcomponent, but do not modify or copy the input component any behavior in.

const EnhancedComponent = higherOrderComponent(WrappedComponent);
Copy after login

HOC can be used for many of the following use cases

  • Code reuse, logic and bootstrapping abstractions
  • Render hijacking
  • state abstractions and operations
  • props processing

Question 8: What is the role of calling super in the constructor and passing props as a parameter?

Topic: React
Difficulty: ⭐⭐

The subclass constructor cannot be used until the super() method is calledthis Quotes, the same goes for ES6 subclasses. The main reason for passing props parameters to the super() call is to be able to obtain the incoming props through this.props in the child constructor .

Passing props

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    console.log(this.props);  // { name: &#39;sudheer&#39;,age: 30 }
  }
}
Copy after login

Not passing props

class MyComponent extends React.Component {
  constructor(props) {
    super();
    console.log(this.props); // undefined
    // 但是 Props 参数仍然可用
    console.log(props); // Prints { name: &#39;sudheer&#39;,age: 30 }
  }

  render() {
    // 构造函数外部不受影响
    console.log(this.props) // { name: &#39;sudheer&#39;,age: 30 }
  }
}
Copy after login

The above example reveals something. The behavior of props is different only inside the constructor, it is the same outside the constructor.

Question 9: What is a control component?

Theme: React
Difficulty: ⭐⭐⭐

In HTML, form elements such as <input>, <textarea&gt ; and <select> usually maintain their own state and update based on user input. When the user submits the form, the values ​​from the above elements will be sent with the form.

而 React 的工作方式则不同。包含表单的组件将跟踪其状态中的输入值,并在每次回调函数(例如onChange)触发时重新渲染组件,因为状态被更新。以这种方式由 React 控制其值的输入表单元素称为受控组件

问题 10:如何 React.createElement ?

主题: React
难度: ⭐⭐⭐

问题:

const element = (
  <h1 className="greeting">
    Hello, world!
  </h1>
)
Copy after login

上述代码如何使用 React.createElement 来实现:

const element = React.createElement(
  &#39;h1&#39;,
  {className: &#39;greeting&#39;},
  &#39;Hello, world!&#39;
);
Copy after login

问题 11:讲讲什么是 JSX ?

主题: React
难度: ⭐⭐⭐

Facebook 第一次发布 React 时,他们还引入了一种新的 JS 方言 JSX,将原始 HTML 模板嵌入到 JS 代码中。JSX 代码本身不能被浏览器读取,必须使用Babelwebpack等工具将其转换为传统的JS。很多开发人员就能无意识使用 JSX,因为它已经与 React 结合在一直了。

class MyComponent extends React.Component {
  render() {
    let props = this.props;  
    return (
      <p className="my-component">
      <a href={props.url}>{props.name}</a>
      </p>
    );
  }
}
Copy after login

问题 12:根据下面定义的代码,可以找出存在的两个问题吗 ?

主题: React
难度: ⭐⭐⭐

请看下面的代码:

35 interview questions you must know and master React

答案:

1.在构造函数没有将 props 传递给 super,它应该包括以下行

constructor(props) {
  super(props);
  // ...
}
Copy after login

2.事件监听器(通过addEventListener()分配时)的作用域不正确,因为 ES6 不提供自动绑定。因此,开发人员可以在构造函数中重新分配clickHandler来包含正确的绑定:

constructor(props) {
  super(props);
  this.clickHandler = this.clickHandler.bind(this);
  // ...
}
Copy after login

问题 13:为什么不直接更新 state 呢 ?

主题: React
难度: ⭐⭐⭐

如果试图直接更新 state ,则不会重新渲染组件。

 // 错误
 This.state.message = &#39;Hello world&#39;;
Copy after login

需要使用setState()方法来更新 state。它调度对组件state对象的更新。当state改变时,组件通过重新渲染来响应:

// 正确做法
This.setState({message: ‘Hello World’});
Copy after login

问题 14:React 组件生命周期有哪些不同阶段?

主题: React
难度: ⭐⭐⭐

在组件生命周期中有四个不同的阶段:

  1. Initialization:在这个阶段,组件准备设置初始化状态和默认属性。
  2. Mounting:react 组件已经准备好挂载到浏览器 DOM 中。这个阶段包括componentWillMountcomponentDidMount生命周期方法。
  3. Updating:在这个阶段,组件以两种方式更新,发送新的 props 和 state 状态。此阶段包括shouldComponentUpdatecomponentWillUpdatecomponentDidUpdate生命周期方法。
  4. Unmounting:在这个阶段,组件已经不再被需要了,它从浏览器 DOM 中卸载下来。这个阶段包含 componentWillUnmount 生命周期方法。

除以上四个常用生命周期外,还有一个错误处理的阶段:

Error Handling:在这个阶段,不论在渲染的过程中,还是在生命周期方法中或是在任何子组件的构造函数中发生错误,该组件都会被调用。这个阶段包含了 componentDidCatch 生命周期方法。

35 interview questions you must know and master React

问题 15:React 的生命周期方法有哪些?

主题: React
难度: ⭐⭐⭐
  • componentWillMount:在渲染之前执行,用于根组件中的 App 级配置。
  • componentDidMount:在第一次渲染之后执行,可以在这里做AJAX请求,DOM 的操作或状态更新以及设置事件监听器。
  • componentWillReceiveProps:在初始化render的时候不会执行,它会在组件接受到新的状态(Props)时被触发,一般用于父组件状态更新时子组件的重新渲染
  • shouldComponentUpdate:确定是否更新组件。默认情况下,它返回true。如果确定在 stateprops 更新后组件不需要在重新渲染,则可以返回false,这是一个提高性能的方法。
  • componentWillUpdate:在shouldComponentUpdate返回 true 确定要更新组件之前件之前执行。
  • componentDidUpdate:它主要用于更新DOM以响应propsstate更改。
  • componentWillUnmount:它用于取消任何的网络请求,或删除与组件关联的所有事件监听器。

问题 16:这三个点(...)在 React 干嘛用的?

主题: React
难度: ⭐⭐⭐

... 在React(使用JSX)代码中做什么?它叫什么?

<Modal {...this.props} title=&#39;Modal heading&#39;  animation={false}/>
Copy after login

这个叫扩展操作符号或者展开操作符,例如,如果this.props包含a:1b:2,则

<Modal {...this.props} title=&#39;Modal heading&#39; animation={false}>
Copy after login

等价于下面内容:

<Modal a={this.props.a} b={this.props.b} title=&#39;Modal heading&#39; animation={false}>
Copy after login

扩展符号不仅适用于该用例,而且对于创建具有现有对象的大多数(或全部)属性的新对象非常方便,在更新state 咱们就经常这么做:

this.setState(prevState => {
    return {foo: {...prevState.foo, a: "updated"}};
});
Copy after login

问题 17:使用 React Hooks 好处是啥?

主题: React
难度: ⭐⭐⭐

首先,Hooks 通常支持提取和重用跨多个组件通用的有状态逻辑,而无需承担高阶组件或渲染 props 的负担。Hooks 可以轻松地操作函数组件的状态,而不需要将它们转换为类组件。

Hooks 在类中不起作用,通过使用它们,咱们可以完全避免使用生命周期方法,例如 componentDidMountcomponentDidUpdatecomponentWillUnmount。相反,使用像useEffect这样的内置钩子。

问题 18:什么是 React Hooks?

主题: React
难度: ⭐⭐⭐

Hooks是 React 16.8 中的新添加内容。它们允许在不编写类的情况下使用state和其他 React 特性。使用 Hooks,可以从组件中提取有状态逻辑,这样就可以独立地测试和重用它。Hooks 允许咱们在不改变组件层次结构的情况下重用有状态逻辑,这样在许多组件之间或与社区共享 Hooks 变得很容易。

问题 19:React 中的 useState() 是什么?

主题: React
难度: ⭐⭐⭐

下面说明useState(0)的用途:

...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...

const setCount = () => {
    setCounter(count + 1);
    setMoreStuff(...);
    ...
};
Copy after login

useState 是一个内置的 React Hook。useState(0) 返回一个元组,其中第一个参数count是计数器的当前状态,setCounter 提供更新计数器状态的方法。

咱们可以在任何地方使用setCounter方法更新计数状态-在这种情况下,咱们在setCount函数内部使用它可以做更多的事情,使用 Hooks,能够使咱们的代码保持更多功能,还可以避免过多使用基于类的组件。

问题 20:React 中的StrictMode(严格模式)是什么?

主题: React
难度: ⭐⭐⭐

React 的StrictMode是一种辅助组件,可以帮助咱们编写更好的 react 组件,可以使用<StrictMode />包装一组组件,并且可以帮咱们以下检查:

  • 验证内部组件是否遵循某些推荐做法,如果没有,会在控制台给出警告。
  • 验证是否使用的已经废弃的方法,如果有,会在控制台给出警告。
  • 通过识别潜在的风险预防一些副作用。

问题 21:为什么类方法需要绑定到类实例?

主题: React
难度: ⭐⭐⭐

在 JS 中,this 值会根据当前上下文变化。在 React 类组件方法中,开发人员通常希望 this 引用组件的当前实例,因此有必要将这些方法绑定到实例。通常这是在构造函数中完成的:

class SubmitButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isFormSubmitted: false
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit() {
    this.setState({
      isFormSubmitted: true
    });
  }

  render() {
    return (
      <button onClick={this.handleSubmit}>Submit</button>
    )
  }
}
Copy after login

问题 22:什么是 prop drilling,如何避免?

主题: React
难度: ⭐⭐⭐

在构建 React 应用程序时,在多层嵌套组件来使用另一个嵌套组件提供的数据。最简单的方法是将一个 prop 从每个组件一层层的传递下去,从源组件传递到深层嵌套组件,这叫做prop drilling

prop drilling的主要缺点是原本不需要数据的组件变得不必要地复杂,并且难以维护。

为了避免prop drilling,一种常用的方法是使用React Context。通过定义提供数据的Provider组件,并允许嵌套的组件通过Consumer组件或useContext Hook 使用上下文数据。

问题 23:描述 Flux 与 MVC?

主题: React
难度: ⭐⭐⭐

传统的 MVC 模式在分离数据(Model)、UI(View和逻辑(Controller)方面工作得很好,但是 MVC 架构经常遇到两个主要问题:

数据流不够清晰:跨视图发生的级联更新常常会导致混乱的事件网络,难于调试。

缺乏数据完整性:模型数据可以在任何地方发生突变,从而在整个UI中产生不可预测的结果。

使用 Flux 模式的复杂用户界面不再遭受级联更新,任何给定的React 组件都能够根据 store 提供的数据重建其状态。Flux 模式还通过限制对共享数据的直接访问来加强数据完整性。

问题 24:受控组件和非受控组件区别是啥?

主题: React
难度: ⭐⭐⭐
  • 受控组件是 React 控制中的组件,并且是表单数据真实的唯一来源。
  • 非受控组件是由 DOM 处理表单数据的地方,而不是在 React 组件中。

尽管非受控组件通常更易于实现,因为只需使用refs即可从 DOM 中获取值,但通常建议优先选择受控制的组件,而不是非受控制的组件。

这样做的主要原因是受控组件支持即时字段验证,允许有条件地禁用/启用按钮,强制输入格式。

问题 25:这段代码有什么问题吗?

主题: React
难度: ⭐⭐⭐⭐

这段代码有什么问题:

this.setState((prevState, props) => {
  return {
    streak: prevState.streak + props.count
  }
})
Copy after login

答案:

没有什么问题。这种方式很少被使用,咱们可以将一个函数传递给setState,该函数接收上一个 state 的值和当前的props,并返回一个新的状态,如果咱们需要根据以前的状态重新设置状态,推荐使用这种方式。

问题 26:什么是 React Context?

主题: React
难度: ⭐⭐⭐⭐

Context 通过组件树提供了一个传递数据的方法,从而避免了在每一个层级手动的传递 props 属性。

问题 27:什么是 React Fiber?

主题: React
难度: ⭐⭐⭐⭐

Fiber 是 React 16 中新的协调引擎或重新实现核心算法。它的主要目标是支持虚拟DOM的增量渲染。React Fiber 的目标是提高其在动画、布局、手势、暂停、中止或重用等方面的适用性,并为不同类型的更新分配优先级,以及新的并发原语。

React Fiber 的目标是增强其在动画、布局和手势等领域的适用性。它的主要特性是增量渲染:能够将渲染工作分割成块,并将其分散到多个帧中。

问题 28:如何在 ReactJS 的 Props上应用验证?

主题: React
难度: ⭐⭐⭐⭐

当应用程序在开发模式下运行时,React 将自动检查咱们在组件上设置的所有 props,以确保它们具有正确的数据类型。对于不正确的类型,开发模式下会在控制台中生成警告消息,而在生产模式中由于性能影响而禁用它。强制的 propsisRequired定义的。

下面是一组预定义的 prop 类型:

  • React.PropTypes.string
  • React.PropTypes.number
  • React.PropTypes.func
  • React.PropTypes.node
  • React.PropTypes.bool

例如,咱们为用户组件定义了如下的propTypes

import PropTypes from &#39;prop-types&#39;;

class User extends React.Component {
  render() {
    return (
      <h1>Welcome, {this.props.name}</h1>
      <h2>Age, {this.props.age}
    );
  }
}

User.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number.isRequired
};
Copy after login

问题 29:在 React 中使用构造函数和 getInitialState 有什么区别?

主题: React
难度: ⭐⭐⭐⭐

构造函数和getInitialState之间的区别就是ES6ES5本身的区别。在使用ES6类时,应该在构造函数中初始化state,并在使用React.createClass时定义getInitialState方法。

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { /* initial state */ };
  }
}
Copy after login

等价于:

var MyComponent = React.createClass({
  getInitialState() {
    return { /* initial state */ };
  },
});
Copy after login

问题 30:如何有条件地向 React 组件添加属性?

主题: React
难度: ⭐⭐⭐⭐

对于某些属性,React 非常聪明,如果传递给它的值是虚值,可以省略该属性。例如:

var InputComponent = React.createClass({
    render: function() {
      var required = true;
      var disabled = false;

      return (
        <input type="text" disabled={disabled} required={required} />
      );
    }
});
Copy after login

渲染结果:

<input type="text" required>
Copy after login

另一种可能的方法是:

var condition = true;

var component = (
  <p
    value="foo"
    { ...( condition && { disabled: true } ) } />
);
Copy after login

问题 31:Hooks会取代 render props 和高阶组件吗?

主题: React
难度: ⭐⭐⭐⭐

通常,render props和高阶组件仅渲染一个子组件。React团队认为,Hooks 是服务此用例的更简单方法。

这两种模式仍然有一席之地(例如,一个虚拟的 scroller 组件可能有一个 renderItem prop,或者一个可视化的容器组件可能有它自己的 DOM 结构)。但在大多数情况下,Hooks 就足够了,可以帮助减少树中的嵌套。

问题 32:如何避免组件的重新渲染?

主题: React
难度: ⭐⭐⭐⭐

React 中最常见的问题之一是组件不必要地重新渲染。React 提供了两个方法,在这些情况下非常有用:

  • React.memo():这可以防止不必要地重新渲染函数组件
  • PureComponent:这可以防止不必要地重新渲染类组件

这两种方法都依赖于对传递给组件的props的浅比较,如果 props 没有改变,那么组件将不会重新渲染。虽然这两种工具都非常有用,但是浅比较会带来额外的性能损失,因此如果使用不当,这两种方法都会对性能产生负面影响。

通过使用 React Profiler,可以在使用这些方法前后对性能进行测量,从而确保通过进行给定的更改来实际改进性能。

问题 33:什么是纯函数?

主题: React
难度: ⭐⭐⭐⭐⭐

纯函数是不依赖并且不会在其作用域之外修改变量状态的函数。本质上,纯函数始终在给定相同参数的情况下返回相同结果。

问题 34:当调用setState时,React render 是如何工作的?

主题: React
难度: ⭐⭐⭐⭐⭐

咱们可以将"render"分为两个步骤:

  1. 虚拟 DOM 渲染:当render方法被调用时,它返回一个新的组件的虚拟 DOM 结构。当调用setState()时,render会被再次调用,因为默认情况下shouldComponentUpdate总是返回true,所以默认情况下 React 是没有优化的。
  2. 原生 DOM 渲染:React 只会在虚拟DOM中修改真实DOM节点,而且修改的次数非常少——这是很棒的React特性,它优化了真实DOM的变化,使React变得更快。

问题 35:如何避免在React重新绑定实例?

主题: React
难度: ⭐⭐⭐⭐⭐

有几种常用方法可以避免在 React 中绑定方法:

1.将事件处理程序定义为内联箭头函数

class SubmitButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isFormSubmitted: false
    };
  }

  render() {
    return (
      <button onClick={() => {
        this.setState({ isFormSubmitted: true });
      }}>Submit</button>
    )
  }
}
Copy after login

2.使用箭头函数来定义方法:

class SubmitButton extends React.Component {
  state = {
    isFormSubmitted: false
  }

  handleSubmit = () => {
    this.setState({
      isFormSubmitted: true
    });
  }

  render() {
    return (
      <button onClick={this.handleSubmit}>Submit</button>
    )
  }
}
Copy after login

3.使用带有 Hooks 的函数组件

const SubmitButton = () => {
  const [isFormSubmitted, setIsFormSubmitted] = useState(false);

  return (
    <button onClick={() => {
        setIsFormSubmitted(true);
    }}>Submit</button>
  )
};
Copy after login
本文转载自:https://segmentfault.com/a/1190000020912300

相关教程推荐:React视频教程

this
No Yes

The above is the detailed content of 35 interview questions you must know and master React. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!