如何为 useReducer 输入状态和分派 - 打字稿和反应

pet*_*gan 11 typescript ecmascript-6 reactjs react-hooks

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

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

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

动作.ts

export const setTeam = (team: string | null) => ({
  type: 'SET_TEAM',
  team,
});
Run Code Online (Sandbox Code Playgroud)

减速机.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;
  }
};
Run Code Online (Sandbox Code Playgroud)

应用程序.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>
  )
}
Run Code Online (Sandbox Code Playgroud)

团队.tsx

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

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

   return <span onClick={() => dispatch(setTeam('LFC'))}>LFC</span>
}
Run Code Online (Sandbox Code Playgroud)

Asa*_*viv 16

如果你想通过上下文传递状态和分派,你必须在上下文中输入它,你可以只使用这一行,但如果你想要类型安全,请进一步阅读

const GlobalContext = React.createContext<[State, React.Dispatch<any>]>([
  { team: null },
  () => {},
])
Run Code Online (Sandbox Code Playgroud)

如果您希望操作的类型安全,您可以将<any>内部更改React.Dispatch为您的操作类型,您还需要在减速器内键入操作

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

type State = {
  team: string | null
}

export const initialState: State = {
  team: null,
}

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

type RemoveTeamAction = {
  type: typeof TeamTypes.REMOVE_TEAM
}

type TeamActionTypes = SetTeamAction | RemoveTeamAction

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

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

export const reducer = (state: State, action: TeamActionTypes): State => {
  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]}></GlobalContext.Provider>
  )
}
Run Code Online (Sandbox Code Playgroud)