react如何存取全局变量
使用Context API
React的Context API是官方推荐的全局状态管理方案,适用于跨组件共享数据。创建Context后,通过Provider传递数据,子组件通过useContext或Consumer访问。
import React, { createContext, useContext } from 'react';
const GlobalContext = createContext();
export function App() {
return (
<GlobalContext.Provider value={{ theme: 'dark' }}>
<ChildComponent />
</GlobalContext.Provider>
);
}
function ChildComponent() {
const { theme } = useContext(GlobalContext);
return <div>Current theme: {theme}</div>;
}
使用状态管理库
Redux或MobX等第三方库适合复杂全局状态管理。以Redux为例,通过Store集中管理状态,组件通过useSelector和useDispatch访问或更新。
import { configureStore, createSlice } from '@reduxjs/toolkit';
import { Provider, useSelector, useDispatch } from 'react-redux';
const globalSlice = createSlice({
name: 'global',
initialState: { count: 0 },
reducers: {
increment: (state) => { state.count += 1; }
}
});
const store = configureStore({ reducer: globalSlice.reducer });
function Counter() {
const count = useSelector((state) => state.global.count);
const dispatch = useDispatch();
return <button onClick={() => dispatch(globalSlice.actions.increment())}>{count}</button>;
}
使用自定义Hook封装
通过自定义Hook封装全局变量,结合useState或useReducer实现简易全局状态管理。适合小型应用或特定场景。
import { useState, useEffect } from 'react';
let globalState = {};
const listeners = new Set();
export function useGlobalState(key, initialValue) {
const [state, setState] = useState(globalState[key] || initialValue);
useEffect(() => {
const listener = () => setState(globalState[key]);
listeners.add(listener);
return () => listeners.delete(listener);
}, [key]);
const setGlobalState = (value) => {
globalState = { ...globalState, [key]: value };
listeners.forEach((listener) => listener());
};
return [state, setGlobalState];
}
使用Window对象
在浏览器环境中,可通过window对象挂载全局变量。此方法简单但缺乏响应式更新,需谨慎使用。

window.appConfig = { apiUrl: 'https://api.example.com' };
function ConfigDisplay() {
return <div>API endpoint: {window.appConfig.apiUrl}</div>;
}
注意事项
- 性能优化: Context API可能导致不必要的渲染,可通过拆分Context或使用
memo优化。 - 类型安全: 使用TypeScript时,为全局变量定义明确类型以避免运行时错误。
- 服务端渲染: 避免直接使用
window对象,需通过环境变量或动态检测处理。






