react如何设置全局变量
在React中设置全局变量
React本身不提供全局变量的概念,但可以通过以下几种方式实现类似功能:
使用Context API
创建全局状态管理的最常见方法是使用React的Context API:
import React, { createContext, useContext } from 'react';
const GlobalContext = createContext();
export function GlobalProvider({ children }) {
const [globalState, setGlobalState] = React.useState({
theme: 'light',
user: null
});
return (
<GlobalContext.Provider value={{ globalState, setGlobalState }}>
{children}
</GlobalContext.Provider>
);
}
export function useGlobal() {
return useContext(GlobalContext);
}
在根组件中包裹应用:
function App() {
return (
<GlobalProvider>
{/* 其他组件 */}
</GlobalProvider>
);
}
在子组件中使用:
function ChildComponent() {
const { globalState, setGlobalState } = useGlobal();
// 访问和修改全局状态
}
使用状态管理库
Redux、MobX等状态管理库专门设计用于管理全局状态:
// Redux示例
import { configureStore } from '@reduxjs/toolkit';
import { Provider } from 'react-redux';
const store = configureStore({
reducer: {
// 定义reducers
}
});
function App() {
return (
<Provider store={store}>
{/* 其他组件 */}
</Provider>
);
}
使用Window对象
简单但不够React的方式是直接挂载到window对象:
// 设置
window.globalConfig = {
apiUrl: 'https://api.example.com',
theme: 'dark'
};
// 使用
console.log(window.globalConfig.apiUrl);
使用环境变量
通过.env文件定义全局配置:
REACT_APP_API_URL=https://api.example.com
REACT_APP_THEME=dark
在组件中访问:
const apiUrl = process.env.REACT_APP_API_URL;
使用自定义Hook
创建可重用的自定义Hook来管理全局状态:
import { useState, useEffect } from 'react';
function useGlobalVariable() {
const [globalVar, setGlobalVar] = useState(null);
useEffect(() => {
// 初始化逻辑
}, []);
return [globalVar, setGlobalVar];
}
每种方法适用于不同场景,Context API适合中小型应用,Redux等库适合复杂状态管理,window对象适合简单跨组件共享,环境变量适合配置项。







