1.准备
import React, { useReducer } from 'react'; // import { useIntl } from 'react-intl'; // 用于国际化 后续在写入暂时无效
2.用于存放数据的函数
const initialGlobalState = { VariantOne: null, variantTow: null, };
3.用于更改数据的函数
const globalStateReducer = (state, action) => { switch (action.type) { case 'setAvatarUrl': { // 用于定义修改是的键 const { avatarUrl } = action; // 用于接收修改 return { ...state, avatarUrl, }; } case 'setSortsName': { const { SortsName } = action; return { ...state, SortsName, }; } case 'setVariantOne': { const { VariantOne } = action; return { ...state, VariantOne, }; } case 'setVariantTow': { const { VariantTow } = action; return { ...state, VariantTow, }; } default: return state; } };
4.导出
export const GlobalStateProvider = ({ children }) => { const [globalState, globalStateDispatch] = useReducer(globalStateReducer, initialGlobalState); // const intl = useIntl(); return ( <GlobalStateContext.Provider value={{ globalState, globalStateDispatch, intl }}> // 无视intl {children} </GlobalStateContext.Provider> ); }; const GlobalStateContext = React.createContext({}); export default GlobalStateContext;
5.调用 放到全局让他包起来
import { GlobalStateProvider } from 'components/GlobalStateContext'; <GlobalStateProvider> //包起来 里面的组件就可以使用 <AppComponent /> </GlobalStateProvider>
6.更改和获取
1.类组件
// 修改 this.context.globalStateDispatch({ type: 'setVariantOne', VariantOne: false }); this.context.globalStateDispatch({ type: 'setVariantTow', VariantTow: false }); // 获取使用 this.context.globalState.VariantOne; this.context.globalState.VariantTow; globalState与globalStateDispatch 为上面定义导出的函数
2.函数组件
// 在获取前先把结构useContext出来 import React, { useContext } from 'react'; //使用时 const Context = useContext(GlobalStateContext); // 更改 Context.globalStateDispatch({ type: 'setVariantOne', VariantOne: true }); // 定义修改 Context.globalStateDispatch({ type: 'setVariantTow', VariantTow: true }); // 获取 Context.globalState.VariantOne; Context.globalState.VariantTow;
标签:createContext,VariantOne,const,useReducer,globalStateDispatch,React,state,global From: https://www.cnblogs.com/Dluea/p/17225748.html