react如何使用全局变量
使用 Context API 创建全局变量
React 的 Context API 是官方推荐的全局状态管理方案,适合跨组件共享数据。通过 React.createContext 创建上下文,再通过 Provider 传递数据,子组件通过 useContext 或 Consumer 访问。
// 创建 Context
const GlobalContext = React.createContext();
// 在根组件提供数据
function App() {
const [globalData, setGlobalData] = useState({});
return (
<GlobalContext.Provider value={{ globalData, setGlobalData }}>
<ChildComponent />
</GlobalContext.Provider>
);
}
// 子组件消费数据
function ChildComponent() {
const { globalData } = useContext(GlobalContext);
return <div>{globalData.key}</div>;
}
使用 Redux 管理全局状态
Redux 是流行的第三方状态管理库,适合复杂应用。通过 store 集中管理状态,组件通过 connect 或 useSelector 访问。
// 创建 store
import { createStore } from 'redux';
const initialState = { count: 0 };
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT': return { ...state, count: state.count + 1 };
default: return state;
}
};
const store = createStore(reducer);
// 在根组件注入 store
import { Provider } from 'react-redux';
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
// 组件连接 store
function Counter() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return <button onClick={() => dispatch({ type: 'INCREMENT' })}>{count}</button>;
}
使用 Window 对象挂载变量
在浏览器环境中,可以通过 window 对象直接挂载全局变量,但这种方式缺乏响应式更新,通常不推荐。
// 设置全局变量
window.appConfig = { apiUrl: 'https://example.com' };
// 组件中使用
function Component() {
return <div>{window.appConfig.apiUrl}</div>;
}
使用自定义 Hook 封装全局逻辑
通过自定义 Hook 可以封装全局状态逻辑,结合 useState 或 useReducer 实现响应式更新。
// 创建自定义 Hook
function useGlobalState() {
const [state, setState] = useState({ theme: 'light' });
const toggleTheme = () => setState(prev => ({
...prev,
theme: prev.theme === 'light' ? 'dark' : 'light'
}));
return { ...state, toggleTheme };
}
// 组件中使用
function ThemeToggle() {
const { theme, toggleTheme } = useGlobalState();
return <button onClick={toggleTheme}>Current: {theme}</button>;
}
使用 Zustand 轻量级状态管理
Zustand 是更轻量的状态管理库,API 简洁,适合中小型应用。
import create from 'zustand';
// 创建 store
const useStore = create(set => ({
bears: 0,
increase: () => set(state => ({ bears: state.bears + 1 })),
}));
// 组件中使用
function BearCounter() {
const bears = useStore(state => state.bears);
const increase = useStore(state => state.increase);
return <button onClick={increase}>{bears}</button>;
}
注意事项
- 性能优化: Context 的频繁更新会导致所有消费者重新渲染,可通过拆分上下文或使用
useMemo优化。 - 类型安全: 使用 TypeScript 时,为全局状态定义明确的类型接口。
- 服务端渲染: 在 Next.js 等框架中,避免直接使用
window对象,需通过条件渲染或状态注入处理。







