reactjs - 如何为以下 contextapi 代码的 useReducer useContext 设置 Typescript 类型?

标签 reactjs typescript context-api react-typescript use-reducer

我想在以下代码中使用正确的 TS 类型而不是任何类型。我是 TS 的新手,请帮忙...
如何为以下上下文 API 代码的 useReducer useContext 设置 typescript 类型:

import React, {createContext, Dispatch} from 'react';
import {firebaseUser} from '../@types/User';

interface Actions {
  SET_IMAGENAME: string;
  SET_USER: string;
}

export const Actions: Actions = {
  SET_IMAGENAME: 'SET_IMAGENAME',
  SET_USER: 'SET_USER',
};

function action(type: string) {
  return {type};
}

function actionPayload(type: string, payload: any) { //here
  return {type, payload};
}

export const Dispatches = {
  setImageName: action,
  setUser: actionPayload,
};

interface State {
  imgName: string;
  user: firebaseUser;
}

const initialState = {
  imgName: '',
  user: {} as firebaseUser,
};

function reducer(state = initialState, action: {type: string; payload: any}) { //here
  switch (action.type) {
    case Actions.SET_IMAGENAME:
      return {...state, imgName: 'sample image'};
    case Actions.SET_USER:
      return {...state, user: action.payload};
    default:
      return state;
  }
}

export const Store = createContext<{
  state: State;
  dispatch: Dispatch<any>; //here
}>({
  state: initialState,
  dispatch: () => null,
});

export function StoreProvider({children}: JSX.ElementChildrenAttribute): JSX.Element {
  const [state, dispatch] = React.useReducer(reducer, initialState);
  return <Store.Provider value={{state, dispatch}}>{children}</Store.Provider>;
}
任何人都可以帮助我这将不胜感激?
谢谢你

最佳答案

我希望这个解决方案会给出好主意。
https://gist.github.com/sw-yx/f18fe6dd4c43fddb3a4971e80114a052
https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/context/#extended-example

export function createCtx<StateType, ActionType>(
  reducer: React.Reducer<StateType, ActionType>,
  initialState: StateType,
) {
  const defaultDispatch: React.Dispatch<ActionType> = () => initialState // we never actually use this
  const ctx = React.createContext({
    state: initialState,
    dispatch: defaultDispatch, // just to mock out the dispatch type and make it not optioanl
  })
  function Provider(props: React.PropsWithChildren<{}>) {
    const [state, dispatch] = React.useReducer<React.Reducer<StateType, ActionType>>(reducer, initialState)
    return <ctx.Provider value={{ state, dispatch }} {...props} />
  }
  return [ctx, Provider] as const
}
// usage
const initialState = { count: 0 }
type AppState = typeof initialState
type Action =
  | { type: 'increment' }
  | { type: 'add'; payload: number }
  | { type: 'minus'; payload: number }
  | { type: 'decrement' }

function reducer(state: AppState, action: Action): AppState {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 }
    case 'decrement':
      return { count: state.count - 1 }
    case 'add':
      return { count: state.count + action.payload }
    case 'minus':
      return { count: state.count - action.payload }
    default:
      throw new Error()
  }
}
const [ctx, CountProvider] = createCtx(reducer, initialState)
export const CountContext = ctx

// top level example usage
export function App() {
  return (
    <CountProvider>
      <Counter />
    </CountProvider>
  )
}

// example usage inside a component
function Counter() {
  const { state, dispatch } = React.useContext(CountContext)
  return (
    <div>
      Count: {state.count}
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'add', payload: 5 })}>+5</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
      <button onClick={() => dispatch({ type: 'minus', payload: 5 })}>+5</button>
    </div>
  )
}

关于reactjs - 如何为以下 contextapi 代码的 useReducer useContext 设置 Typescript 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62748250/

相关文章:

reactjs - 大量使用本地存储是一种好的做法吗?

Angular 6浏览器检测?

javascript - 什么会导致 typescript 输出的 map 文件中出现意外标记?

javascript - Ant Design Dropdown - 访问子菜单中的 props 值 [ React ]

javascript - 如何检查元素是否有效 JSX

angular - 获取通用 Angular 服务中的类型名称

reactjs - 将状态和分派(dispatch)放入单独的上下文提供程序是否可以防止不必要的重新渲染?

reactjs - useEffect 和上下文 api

javascript - 当状态对象发生变化时更新上下文