当前位置: 首页> 科技> 互联网 > React进阶

React进阶

时间:2025/7/13 12:09:41来源:https://blog.csdn.net/weixin_47251999/article/details/139867338 浏览次数:0次

State保存在React中,并不在组件中【State is actually held inside React!】

当组件A被替换为组件B时,B组件可以继续使用A组件的状态值!
条件:

  1. 相同组件
  2. 在UI树🌲相同位置
  3. 组件key相同

一个JSX语句代表一个UI树🌲组件节点
UI🌲同一个位置:
在这里插入图片描述
UI🌲不同位置:
在这里插入图片描述

Reducer:提取状态更新逻辑(https://react.nodejs.cn/learn/extracting-state-logic-into-a-reducer)

Context:上下文

实现当前组件下所有子组件共享context数据源,代替数据参数传递。
在这里插入图片描述

Context常用场景

  • 主题Theming:应用有多种主题
  • 用户账号account:存储用户账号、机构信息,方便全局使用
  • 路由Routing:存储当前路径,以便组件判断自己是否需要显示
  • 全局共享变量:方便远程组件读写

使用Context

创建Context

import { createContext } from 'react';export const LevelContext = createContext(1);
  • LevelContext:context名字,随便起,一般是:变量名+Context
  • 1:当前Context默认值,可以为任意类型
  • export:导出当前Context

赋值Context

import { LevelContext } from './LevelContext.js';export default function Section({ level, children }) {return (<section className="section"><LevelContext.Provider value={level}>{children}</LevelContext.Provider></section>);
}
  • LevelContext.Provider:Context名.+Provider 标签规定Context使用范围,当前标签下的所有组件都可以使用该Context
  • value={level}:将<Section>标签的level变量赋值给Context

取值Context

import { useContext } from 'react';
import { LevelContext } from './LevelContext.js';export default function Heading({ children }) {const level = useContext(LevelContext);switch (level) {case 1:return <h1>{children}</h1>;default:throw Error('Unknown level: ' + level);}
}
  • useContext:告诉 React <Heading> 组件想要读取最近标签的 LevelContext 的值

使用 Reducer 和上下文进行扩展

关键字:React进阶