如何为useReducer键入状态和调度-键入脚本并做出反应

时间:2019-12-20 22:54:48

标签: reactjs typescript ecmascript-6 react-hooks

我当前在当前设置中看到此错误。

  

输入'({team:string | null;} | {team:string | null;} | {...;} | {...;} | {...;} | Dispatch <... >)[]'缺少“状态”类型的以下属性:teamts(2739)   index.d.ts(290,9):预期的类型来自属性'value',该属性在此处声明为'IntrinsicAttributes&ProviderProps'类型

下面是我的代码,如果需要更多详细信息,请告诉我。

actions.ts

export const setTeam = (team: string | null) => ({
  type: 'SET_TEAM',
  team,
});

reducer.ts

export const initialState = {
  team: null,
};

type State = {
  team: string | null;
};

export const GlobalContext = React.createContext<State | null>(null);

export const reducer = (state: State, action: any) => {
  switch (action.type) {
    case actionTypes.SET_TEAM:
      const team = action.team;
      return {
        ...state,
        team,
      };

    default:
      return state;
  }
};

App.tsx

const App = () => {
  const [state, dispatch] = React.useReducer(reducer, initialState);

  return ( 
    // error with state and dispatch here
    <GlobalContext.Provider value={[state, dispatch]}>
        ...App code
    </GlobalContext.Provider>
  )
}

Team.tsx

import { GlobalContext } from './reducers';
import { setTeam } from './actions';

const Team = () => {
   const [, dispatch] = React.useContext(GlobalContext);

   return <span onClick={() => dispatch(setTeam('LFC'))}>LFC</span>
}

1 个答案:

答案 0 :(得分:1)

如果要通过上下文传递状态和分派,则必须在上下文中键入它,则可以仅使用此行,但是如果要进一步输入安全性,请

const GlobalContext = React.createContext<[State, React.Dispatch<any>]>(null)

如果要为操作键入安全性,可以将<any>内的React.Dispatch更改为操作类型,还需要在化简器中键入操作

enum TeamTypes {
  SET_TEAM = 'SET_TEAM',
  REMOVE_TEAM = 'REMOVE_TEAM',
}

export const setTeam = (team: string | null) => ({
  type: TeamTypes.SET_TEAM,
  team,
});

export const initialState = {
  team: null,
}

type State = {
  team: string | null
}

interface SetTeamAction {
  type: typeof TeamTypes.SET_TEAM
  team: string
}

interface RemoveTeamAction {
  type: typeof TeamTypes.REMOVE_TEAM
}

type TeamActionTypes = 
  | SetTeamAction
  | RemoveTeamAction

export const GlobalContext = React.createContext<[State, React.Dispatch<TeamActionTypes>]>(null)

export const reducer = (state: State, action: TeamActionTypes) => {
  switch (action.type) {
    case TeamTypes.SET_TEAM:
      const { team } = action
      return {
        ...state,
        team,
      }
    default:
      return state
  }
}

const App = () => {
  const [state, dispatch] = React.useReducer(reducer, initialState)

  return ( 
    <GlobalContext.Provider value={[state, dispatch]}>
      ...App code
    </GlobalContext.Provider>
  )
}