【发布时间】:2021-05-11 03:06:36
【问题描述】:
我正在使用带有以下代码的 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;
Login.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 is not a function 在doLogin
【问题讨论】:
-
好奇为什么你觉得需要使用上下文和使用reducer?通过增加额外的复杂性,您获得了什么?只需将登录函数添加到上下文中并直接调用它...
-
对于这个特定的用例来说可能很复杂,但无论如何我需要在我的应用程序级别进行状态管理。所以这只是开始使用和组合所需部分的一种方式
-
@AaronSaunders 此代码不适用于 ionic-react。
标签: reactjs ionic-framework ionic-react