Lang:简体中文

react常见面试题

日期:2025-09-08 / 来源:面试宝典

涵盖核心知识,助你面试通关

在前端开发领域,react是一个非常热门的框架,面试中也经常会被提及。下面就为大家整理一些常见的react面试题。

基础概念类

首先可能会问到react的基本概念。比如什么是jsx?jsx是javascript xml的缩写,它是一种javascript的语法扩展,允许我们在javascript代码中编写类似xml的结构。举个例子:

const element = <h1>hello, world!</h1>; 这就是一个简单的jsx表达式,它最终会被babel等工具编译成react.createelement()函数调用。

还有问到react组件的分类,一般分为函数组件和类组件。函数组件是一个纯函数,接收props作为参数并返回一个react元素。例如:

function welcome(props) { return <h1>hello, {props.name}</h1>; }

类组件则是继承自react.component,需要定义render方法返回react元素。

生命周期相关

react类组件有自己的生命周期,这也是面试的重点。生命周期可以分为挂载阶段、更新阶段和卸载阶段。

挂载阶段常见的钩子函数有componentwillmount、render和componentdidmount。比如componentdidmount,它在组件挂载完成后调用,常用于发起网络请求。示例代码如下:

class example extends react.component { componentdidmount() { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)); } render() { return <div>example component</div>; } }

更新阶段有componentwillreceiveprops、shouldcomponentupdate等。卸载阶段主要是componentwillunmount,用于清理一些资源,比如取消定时器。

状态管理问题

状态管理是react开发中的重要部分。面试可能会问你如何管理组件的状态。在react中,有局部状态和全局状态。

局部状态可以通过this.state在类组件中管理,或者使用usestate钩子在函数组件中管理。例如在函数组件中:

import react, { usestate } from 'react'; function counter() { const [count, setcount] = usestate(0); return ( <div>

you clicked {count} times

</div> ); }

对于全局状态管理,常用的库有redux和mobx。redux通过action、reducer和store来管理状态,保证状态的可预测性。

性能优化方面

性能优化也是常考的点。比如如何避免不必要的渲染。可以使用shouldcomponentupdate生命周期方法在类组件中进行浅比较,决定是否需要重新渲染。

在函数组件中,可以使用react.memo进行包裹,它是一个高阶组件,对props进行浅比较。示例:

const mycomponent = react.memo(function mycomponent(props) { return <div>{props.data}</div>; });

还可以使用purecomponent,它是react.component的子类,内部实现了shouldcomponentupdate的浅比较逻辑。

路由相关问题

在单页面应用中,路由是必不可少的。面试可能会问你react常用的路由库,一般是react router。

react router有browserrouter、hashrouter等。例如使用browserrouter创建路由:

import { browserrouter as router, route, link } from 'react-router-dom'; function app() { return ( <router>

</router> ); }

以上就是一些常见的react面试题,希望对大家有所帮助。

以下为推荐内容

微信二维码