我正在使用带有以下代码的 ionic-react 及其给出的错误
类型 '{ 状态:IState; 调度:React.Dispatch;}' 不可分配给类型 'IState'。对象字面量只能指定已知的属性,并且在类型“IState”中不存在“state”。
代码如下所示
状态.tsx
import React from "react";
export interface IState {
count: number;
loggedIn: boolean;
}
// set the initial values
const initialState = { count: 0, loggedIn: false };
export type ActionType =
| { type: "setLoggedIn"; payload: any }
| { type: "error" };
// create the context
export const Context = React.createContext<IState>(initialState);
export const TheProvider = ({ children }: any): any => {
/**
* @param {*} state
* @param {*} action
*/
const reducer = (state: IState, action: ActionType): IState => {
switch (action.type) {
case "setLoggedIn":
return { ...state, ...action.payload };
default:
throw new Error();
}
};
const [state, dispatch] = React.useReducer(reducer, initialState);
// wrap the application in the provider with the initialized context
return (
<Context.Provider value={{ state, dispatch }}>{children}</Context.Provider>
);
};
export default Context;
登录.tsx
import AppContext, { TheProvider, IState } from './State';
...
const Login: React.FC = () => {
const { state, dispatch } = React.useContext<any>(AppContext);
const doLogin = async () => {
try{
dispatch({
type: 'setLoggedIn',
payload: {loggedIn: false}
})
}catch(err){
console.error("failed to login with erro", err)
}
};
return (
<TheProvider>
<form className="ion-padding">
<IonToolbar>
<IonTitle>Login</IonTitle>
</IonToolbar>
<IonItem style={{paddingTop:'100px'}}>
<IonLabel position="floating">Email</IonLabel>
<IonInput type="email" value={email} onIonChange={e => setEmail(e.detail.value!)}/>
</IonItem>
<IonItem>
<IonLabel position="floating">Password</IonLabel>
<IonInput type="password" value={password} onIonChange={e => setPassword(e.detail.value!)}/>
</IonItem>
<IonItem>
<IonLabel>{errMessage}</IonLabel>
</IonItem>
<IonButton className="ion-margin-top" onClick={doLogin} expand="block">
<IonIcon slot="start" icon={mailOutline} />Login
</IonButton>
</form>
</TheProvider>
)
};
我现在在发送时遇到错误,因为
TypeError:dispatch 不是 doLogin 的函数