无法使用 React/TypeScript 设置 useReducer
Can't setup useReducer with React/TypeScript
我正在学习 TypeScript。我正在尝试设置 useReducer
,但我很难做到。修复可能相当简单,对此深表歉意。这是我的 App.tsx
:
import React, { useReducer } from "react";
import { StartPage } from "./components/StartPage";
import { QuestionsPage } from "./components/QuestionsPage";
type State = {};
type Action = {};
const initialState = {
hasStarted: false // one of the states I'm going to need
};
const reducer = (state: State, action: Action) => {};
export const App = () => {
const [state, dispatch] = useReducer(reducer, initialState); // * error here
return (
<>
<StartPage dispatch={dispatch}/>
<QuestionsPage />
</>
);
};
(也许)很高兴知道:我首先尝试以基本方式设置它,但后来我想根据 hasStarted
是 true
或 false
(我将在 StartPage.tsx
.
中设置
我在这里遇到以下错误(请参阅上面代码段中的 *
):
No overload matches this call.
Overload 1 of 5, '(reducer: ReducerWithoutAction, initializerArg: any, initializer?: undefined): [any, DispatchWithoutAction]', gave the following error.
Argument of type '(state: State, action: Action) => void' is not assignable to parameter of type 'ReducerWithoutAction'.
Overload 2 of 5, '(reducer: (state: State, action: Action) => void, initialState: never, initializer?: undefined): [never, Dispatch]', gave the following error.
Argument of type '{}' is not assignable to parameter of type 'never'.
您在 Typescript 中遇到错误,因为您没有在 reducer 函数中返回任何状态。这将解决问题:
const reducer = (state: State, action: Action) => {
//...logic for updating the state
return state;
};
我正在学习 TypeScript。我正在尝试设置 useReducer
,但我很难做到。修复可能相当简单,对此深表歉意。这是我的 App.tsx
:
import React, { useReducer } from "react";
import { StartPage } from "./components/StartPage";
import { QuestionsPage } from "./components/QuestionsPage";
type State = {};
type Action = {};
const initialState = {
hasStarted: false // one of the states I'm going to need
};
const reducer = (state: State, action: Action) => {};
export const App = () => {
const [state, dispatch] = useReducer(reducer, initialState); // * error here
return (
<>
<StartPage dispatch={dispatch}/>
<QuestionsPage />
</>
);
};
(也许)很高兴知道:我首先尝试以基本方式设置它,但后来我想根据 hasStarted
是 true
或 false
(我将在 StartPage.tsx
.
我在这里遇到以下错误(请参阅上面代码段中的 *
):
No overload matches this call. Overload 1 of 5, '(reducer: ReducerWithoutAction, initializerArg: any, initializer?: undefined): [any, DispatchWithoutAction]', gave the following error.
Argument of type '(state: State, action: Action) => void' is not assignable to parameter of type 'ReducerWithoutAction'.
Overload 2 of 5, '(reducer: (state: State, action: Action) => void, initialState: never, initializer?: undefined): [never, Dispatch]', gave the following error.
Argument of type '{}' is not assignable to parameter of type 'never'.
您在 Typescript 中遇到错误,因为您没有在 reducer 函数中返回任何状态。这将解决问题:
const reducer = (state: State, action: Action) => {
//...logic for updating the state
return state;
};