React Context API 用于在组件树中共享全局状态

1. 创建 Context:

bash 复制代码
const initialValue = {
  age: 0,
  addAge: () => {},
};
export const InfoContext = createContext(initialValue);
createContext(initialValue):

创建一个新的 Context,用来在组件树中提供和消费共享的数据。

这里的 initialValue 定义了 Context 的默认值。initialValue 中有两个属性:

age: 0:代表年龄,初始值为 0。

addAge: () => {}:一个空的函数,目的是定义如何增加年龄。

当没有明确的 Provider 时,使用的就是这个默认的 initialValue。

2. 使用 Context:

bash 复制代码
export const useInfoContext = () => {
  return useContext(InfoContext);
};

useInfoContext:

这是一个自定义的 Hook,内部调用了 React 提供的 useContext Hook。

useContext(InfoContext):该函数返回当前 Context 的值(在 Provider 中设置的值),所以你可以在任何组件中使用 useInfoContext 来访问 age 和 addAge。

它的作用是:让组件能方便地获取到 InfoContext 中的值,并且使得这个值在组件树中任何地方都能共享和消费。

3. 定义 Context Provider:

bash 复制代码
type MyContextProviderProps = {
  children: React.ReactNode;
};

export const MyContextProvider = (props: MyContextProviderProps) => {
  const [age, setAge] = useState(18);
  const addAge = () => {
    setAge((prev) => prev + 1000);
  };

  return (
    <InfoContext.Provider value={{ age, addAge }}>
      {props.children}
    </InfoContext.Provider>
  );
};

MyContextProvider:

这是一个 React 组件,作为 InfoContext 的 Provider,用来为组件树中的所有后代组件提供共享的上下文数据。

useState(18):

初始化 age 为 18,并提供一个 setAge 函数来更新 age 的值。

addAge:

定义了一个函数,使用 setAge 来将 age 增加 1000。当这个函数被调用时,它会修改 age,并触发组件重新渲染。

InfoContext.Provider:

这是 Context 的提供者,它将 age 和 addAge 作为 value 属性传递给它的子组件(props.children)。所有子组件都可以通过 useContext(InfoContext) 来访问这些值。

children: React.ReactNode:

这个类型表示 MyContextProvider 可以接收任何 React 组件作为其子组件,并将它们渲染出来。子组件会自动获得通过 InfoContext.Provider 提供的值。

4. 使用这个 Context:

现在,你可以在你的应用程序中的任何地方使用 useInfoContext 来访问 age 和 addAge:

例如:

bash 复制代码
const SomeComponent = () => {
  const { age, addAge } = useInfoContext();
  
  return (
    <div>
      <p>当前年龄:{age}</p>
      <button onClick={addAge}>增加年龄</button>
    </div>
  );
};

5、MyContextProvider 在哪里放

MyContextProvider 作为一个 Context Provider,应该放在你希望让所有子组件都能够访问该上下文的地方。通常,我们将它放在应用的根组件或某些较大的布局组件中,确保它覆盖了需要访问该上下文的所有组件。

bash 复制代码
 return (
    <MyContextProvider>
      <SomeComponent />
    </MyContextProvider>
  );

这样,MyContextProvider 会为整个子树提供共享的状态,子组件可以通过 useInfoContext 访问该上下文的数据。

6、完整案例

bash 复制代码
import { createContext,useContext,useState } from "react"

const initalValue={
	age: 0;
	addAge:()=>();
}
export const InfoContext = createContext(initalValue);

export const useInfoContext = ()=>{
	return useContext(InfoContext);
}

type MyContextProviderProps ={
	children:React.ReacatNode
}

export MyContextProvider =(props:MyContextProviderProps)=>{
	const [age,setAge]=useState(18)
	const addAge =()=>{
		setAge((prev)=>prev+1000)
	}
	retrurn (
		<InfoContext.Provider value={{ age,addAge}}>
			{props.children}
		</InfoContext.Provider>
	)
}
相关推荐
Spider_Man2 分钟前
栈中藏玄机:从温度到雨水,单调栈的逆袭之路
javascript·算法·leetcode
moddy3 分钟前
新人怎么去做低代码,并且去使用?
前端
风清云淡_A4 分钟前
【Flutter3.8x】flutter从入门到实战基础教程(五):Material Icons图标的使用
前端·flutter
安心不心安8 分钟前
React ahooks——副作用类hooks之useThrottleEffect
前端·react.js·前端框架
jstart千语10 分钟前
【vue】创建响应式数据ref和reactive的区别
前端·javascript·vue.js
肖师叔爱抽风17 分钟前
使用nvm use切换版本时出现虚假成功信息,使用nvm ls,实际显示没有切换成功,解决方法
前端
猩猩程序员19 分钟前
Rust为什么需要Borrow Trait
前端
BUG收容所所长20 分钟前
Zustand状态管理如何驱动低代码平台的数据流?
前端·javascript·设计
司宸23 分钟前
学习笔记十四 —— 嵌套JSON树结构 实现模糊匹配返回搜索路径
前端
盗德24 分钟前
Vue渲染引擎的范式革命:从虚拟DOM到Vapor模式
前端·vue.js