react如何管理全局参数
使用 Context API
Context API 是 React 内置的全局状态管理方案,适合跨组件共享数据。创建一个 Context 并通过 Provider 传递数据,子组件通过 useContext 或 Consumer 访问。
import React, { createContext, useContext } from 'react';
const GlobalContext = createContext();
export const GlobalProvider = ({ children }) => {
const sharedData = { theme: 'dark', user: 'admin' };
return (
<GlobalContext.Provider value={sharedData}>
{children}
</GlobalContext.Provider>
);
};
export const useGlobal = () => useContext(GlobalContext);
在根组件包裹 GlobalProvider,子组件调用 useGlobal() 即可获取全局参数。
使用状态管理库(Redux/Zustand)
对于复杂场景,Redux 或 Zustand 提供更强大的状态管理。以 Zustand 为例:
import create from 'zustand';
const useStore = create((set) => ({
theme: 'light',
setTheme: (newTheme) => set({ theme: newTheme }),
}));
function Component() {
const { theme, setTheme } = useStore();
return <button onClick={() => setTheme('dark')}>{theme}</button>;
}
Zustand 的轻量 API 适合快速实现全局状态共享。
通过 Props 层层传递
适用于简单应用,将参数从顶层组件通过 Props 逐层传递。但嵌套过深时会导致“Prop Drilling”问题,维护性较差。
function Parent() {
const globalParam = { config: 'default' };
return <Child data={globalParam} />;
}
function Child({ data }) {
return <GrandChild data={data} />;
}
使用本地存储(localStorage)
持久化全局参数可通过 localStorage 存储,结合 useEffect 同步状态。
const [theme, setTheme] = useState(localStorage.getItem('theme') || 'light');
useEffect(() => {
localStorage.setItem('theme', theme);
}, [theme]);
此方法适合需要长期保存的配置,如用户主题偏好。
自定义 Hook 封装
将全局逻辑封装为自定义 Hook,方便多处复用。例如:

function useGlobalConfig() {
const [config, setConfig] = useState({ lang: 'en' });
const updateConfig = (key, value) => {
setConfig(prev => ({ ...prev, [key]: value }));
};
return { config, updateConfig };
}
组件中调用 useGlobalConfig() 即可访问和修改全局配置。






