React进阶

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 和上下文进行扩展

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值