React 技术笔记梳理

一、React 基础概念

1.1 什么是 React

  • 定义 :React 是由 Facebook 开发和维护的用于构建用户界面的 JavaScript 库
  • 核心理念 :组件化、声明式编程、虚拟 DOM
  • 特点 :单向数据流、可复用组件、跨平台支持(React Native)

1.2 JSX 语法

ini 复制代码
// 基础JSX
const element = <h1>Hello, React!</
h1>;

// 表达式嵌入
const name = 'World';
const element = <h1>Hello, {name}</
h1>;

// 条件渲染
const isLoggedIn = true;
const element = (
  <div>
    {isLoggedIn ? <UserGreeting /> 
    : <GuestGreeting />}
  </div>
);

// 列表渲染
const numbers = [1, 2, 3];
const listItems = numbers.map((num) 
=> 
  <li key={num}>{num}</li>
);

二、React 组件

2.1 函数组件 vs 类组件

函数组件(推荐) :

javascript 复制代码
function Welcome(props) {
  return <h1>Hello, {props.name}</
  h1>;
}

// 箭头函数形式
const Welcome = ({ name }) => 
<h1>Hello, {name}</h1>;

类组件(传统方式) :

javascript 复制代码
class Welcome extends React.
Component {
  render() {
    return <h1>Hello, {this.props.
    name}</h1>;
  }
}

2.2 Props(属性)

  • 只读性 :props 是从父组件传递的数据,子组件不应修改
  • 默认值 :
javascript 复制代码
function Welcome({ name = 
'Guest' }) {
  return <h1>Hello, {name}</h1>;
}

2.3 State(状态)

  • 组件内部状态 ,用于管理可变数据
  • 状态更新 必须使用 setState (类组件)或 useState (函数组件)

三、React Hooks

3.1 useState

javascript 复制代码
import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState
  (0);
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => 
      setCount(count + 1)}>
        Increment
      </button>
    </div>
  );
}

3.2 useEffect

javascript 复制代码
import { useEffect } from 'react';

function Example() {
  const [count, setCount] = useState
  (0);
  
  // 相当于 componentDidMount + 
  componentDidUpdate
  useEffect(() => {
    document.title = `Count: $
    {count}`;
    
    // 清理函数(相当于 
    componentWillUnmount)
    return () => {
      document.title = 'React App';
    };
  }, [count]); // 依赖数组
  
  return <button onClick={() => 
  setCount(c => c + 1)}>Click</
  button>;
}

3.3 useContext

javascript 复制代码
// 创建Context
const ThemeContext = React.
createContext('light');

// 提供值
function App() {
  return (
    <ThemeContext.Provider 
    value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

// 消费值
function Toolbar() {
  const theme = useContext
  (ThemeContext);
  return <div>Theme: {theme}</div>;
}

3.4 useReducer

javascript 复制代码
const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 
      1 };
    case 'decrement':
      return { count: state.count - 
      1 };
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = 
  useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => 
      dispatch({ type: 
      'increment' })}>+</button>
      <button onClick={() => 
      dispatch({ type: 
      'decrement' })}>-</button>
    </>
  );
}

3.5 useCallback & useMemo

scss 复制代码
// useCallback - 缓存函数引用
const memoizedFn = useCallback(
  () => doSomething(a, b),
  [a, b]
);

// useMemo - 缓存计算结果
const memoizedValue = useMemo(
  () => computeExpensiveValue(a, b),
  [a, b]
);

四、React 18 新特性

4.1 Concurrent Mode(并发模式)

  • 支持可中断渲染,提升大型应用性能
  • 通过 ReactDOM.createRoot() 启用

4.2 Suspense for Data Fetching

javascript 复制代码
const resource = fetchProfileData();

function ProfilePage() {
  return (
    <Suspense fallback={<Loading />}
    >
      <ProfileDetails />
    </Suspense>
  );
}

function ProfileDetails() {
  const user = resource.user.read();
  return <h1>{user.name}</h1>;
}

4.3 Transitions

javascript 复制代码
import { startTransition } from 
'react';

function SearchInput() {
  const [query, setQuery] = useState
  ('');
  
  function handleChange(e) {
    // 紧急更新:立即更新输入框
    setQuery(e.target.value);
    
    // 过渡更新:可中断的非紧急更新
    startTransition(() => {
      // 更新搜索结果
    });
  }
  
  return <input onChange=
  {handleChange} value={query} />;
}

4.4 Server Components(RSC)

javascript 复制代码
// Server Component(服务端渲染)
async function BlogPost({ id }) {
  const post = await db.posts.
  findOne({ id });
  return <article>{post.content}</
  article>;
}

五、状态管理

5.1 Redux

javascript 复制代码
// store.js
import { createStore } from 'redux';

const initialState = { count: 0 };

function counterReducer(state = 
initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 
      1 };
    default:
      return state;
  }
}

const store = createStore
(counterReducer);

// 组件中使用
import { useSelector, useDispatch } 
from 'react-redux';

function Counter() {
  const count = useSelector(state 
  => state.count);
  const dispatch = useDispatch();
  
  return (
    <button onClick={() => dispatch
    ({ type: 'INCREMENT' })}>
      {count}
    </button>
  );
}

5.2 Context API

javascript 复制代码
const AuthContext = createContext
(null);

function AuthProvider({ children }) 
{
  const [user, setUser] = useState
  (null);
  
  const login = (userData) => 
  setUser(userData);
  const logout = () => setUser
  (null);
  
  return (
    <AuthContext.Provider value={{ 
    user, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
}

六、React Router

6.x 版本

ini 复制代码
import { 
  BrowserRouter, 
  Routes, 
  Route, 
  Link,
  useParams,
  useNavigate
} from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/about">About</
        Link>
        <Link to="/users/123">User</
        Link>
      </nav>
      
      <Routes>
        <Route path="/" element=
        {<Home />} />
        <Route path="/about" 
        element={<About />} />
        <Route path="/users/:id" 
        element={<User />} />
      </Routes>
    </BrowserRouter>
  );
}

function User() {
  const params = useParams();
  const navigate = useNavigate();
  
  return (
    <>
      <p>User ID: {params.id}</p>
      <button onClick={() => 
      navigate('/')}>Go Home</
      button>
    </>
  );
}

七、性能优化

7.1 React.memo

javascript 复制代码
const MemoizedComponent = React.memo
(function MyComponent(props) {
  // 仅在props变化时重新渲染
});

7.2 useMemo & useCallback(见3.5节)

7.3 虚拟列表

javascript 复制代码
import { FixedSizeList } from 
'react-window';

function VirtualList({ items }) {
  const renderItem = ({ index, 
  style }) => (
    <div style={style}>
      {items[index].name}
    </div>
  );
  
  return (
    <FixedSizeList
      height={400}
      width="100%"
      itemCount={items.length}
      itemSize={50}
    >
      {renderItem}
    </FixedSizeList>
  );
}

7.4 Code Splitting

javascript 复制代码
import { lazy, Suspense } from 
'react';

const LazyComponent = lazy(() => 
import('./HeavyComponent'));

function App() {
  return (
    <Suspense fallback={<Loading />}
    >
      <LazyComponent />
    </Suspense>
  );
}

八、最佳实践

8.1 组件设计原则

  • 单一职责 :一个组件只做一件事
  • 可复用性 :设计通用、可配置的组件
  • 纯组件 :相同输入产生相同输出

8.2 目录结构

bash 复制代码
src/
├── components/       # 通用组件
│   ├── Button/
│   └── Card/
├── features/         # 功能模块
│   └── user/
│       ├── components/
│       ├── hooks/
│       └── index.js
├── hooks/            # 自定义hooks
├── utils/            # 工具函数
└── App.js

8.3 自定义 Hooks

javascript 复制代码
function useLocalStorage(key, 
initialValue) {
  const [storedValue, 
  setStoredValue] = useState(() => {
    try {
      const item = window.
      localStorage.getItem(key);
      return item ? JSON.parse
      (item) : initialValue;
    } catch {
      return initialValue;
    }
  });
  
  const setValue = (value) => {
    try {
      setStoredValue(value);
      window.localStorage.setItem
      (key, JSON.stringify(value));
    } catch (error) {
      console.error(error);
    }
  };
  
  return [storedValue, setValue];
}

8.4 错误边界

javascript 复制代码
class ErrorBoundary extends React.
Component {
  constructor(props) {
    super(props);
    this.state = { hasError: 
    false };
  }
  
  static getDerivedStateFromError
  (error) {
    return { hasError: true };
  }
  
  componentDidCatch(error, 
  errorInfo) {
    console.error(error, errorInfo);
  }
  
  render() {
    if (this.state.hasError) {
      return <h1>Something went 
      wrong.</h1>;
    }
    return this.props.children;
  }
}

九、测试

9.1 单元测试(Jest + Testing Library)

javascript 复制代码
import { render, screen } from 
'@testing-library/react';
import App from './App';

test('renders welcome message', () 
=> {
  render(<App />);
  const linkElement = screen.
  getByText(/welcome/i);
  expect(linkElement).
  toBeInTheDocument();
});

9.2 快照测试

scss 复制代码
test('renders correctly', () => {
  const { asFragment } = render
  (<MyComponent />);
  expect(asFragment()).
  toMatchSnapshot();
});

十、React 生态

类别 推荐库 路由 React Router 状态管理 Redux Toolkit, Zustand, Jotai 样式 Tailwind CSS, Styled Components 表单 React Hook Form, Formik 数据请求 React Query, SWR 图表 Recharts, Chart.js 动画 Framer Motion, GSAP 测试 Jest, React Testing Library

十一、学习路径总结

  1. 基础阶段 :JSX、组件、Props、State、事件处理
  2. 进阶阶段 :Hooks、Context、React Router、状态管理
  3. 高级阶段 :性能优化、服务端渲染、React 18新特性
  4. 工程化阶段 :TypeScript、测试、构建工具(Vite/Webpack) React 的核心思想是 组件化 和 声明式编程 ,掌握 Hooks 和状态管理是进阶的关键。随着 React 18 的发布,并发特性和 Server Components 正在改变前端开发的方式。
相关推荐
copyer_xyf10 小时前
Python 如何同时做很多事:进程、线程、协程
前端·后端·python
gqk0111 小时前
Delegate.Target/ Method
前端·ui·xhtml
有梦想的程序星空11 小时前
【环境配置】Vue3项目离线化本地部署echarts全攻略
前端·javascript·vue·echarts
IT_陈寒12 小时前
被Vite的动态导入坑了一整天,原来问题出在这
前端·人工智能·后端
薛先生_09912 小时前
vue-路由重定向
前端·javascript·vue.js
橘子星12 小时前
基于 ES6 语法的 NLP 任务模块化开发实践
前端·javascript
玉宇夕落12 小时前
Props的传递学习
前端
月光刺眼12 小时前
JS 底层执行机制探讨:执行上下文、变量提升与调用栈
前端·javascript
|_⊙13 小时前
Linux 信号
运维·服务器·前端
ZC跨境爬虫13 小时前
跟着 MDN 学 JavaScript day_1:什么是 JavaScript?
开发语言·前端·javascript·ecmascript