首先创建一个context文件
import React from 'react';
interface context {
store: any,
dispatch: any,
}
const Context = React.createContext<context>({
store: '',
dispatch: '',
})
export default Context
导出
然后在需要组件传值的父组件中首先引入创建好的context
import Context from "./context";
<Context.Provider value={
{ store, dispatch }}>
<childrenName/>
</Context.Provider>
父组件中定义初始数据,类似于redux
const defaultState = {
//存储数据的默认defaultState
count: 0,
addressInfo: [],
current: 1,
};
const [store, dispatch] = useReducer(reducer, defaultState); //创建reducer
function reducer(state = defaultState, action: any) {
//reducer负责操作数据
switch (action.type) {
case "add":