离子反应类型不可分配 [英] ionic react type is not assignable

查看:68
本文介绍了离子反应类型不可分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将离子反应与以下代码结合使用并给出错误

i am using ionic-react with below code and its giving error

键入'{state:IState;派遣:React.Dispatch;}"不可分配给"IState"类型.对象文字只能指定已知的属性,而状态"在类型"IState"中不存在.

Type '{ state: IState; dispatch: React.Dispatch; }' is not assignable to type 'IState'. Object literal may only specify known properties, and 'state' does not exist in type '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>
    )
};

我现在在发送时出现错误,

i am now getting error on dispatch as

TypeError:分派不是函数在doLogin

TypeError: dispatch is not a function at doLogin

推荐答案

问题出在这两行之间:

export const Context = React.createContext<IState>(initialState);
// ...
<Context.Provider value={{ state, dispatch }}>

如果您希望上下文包含状态和调度,则需要将初始 Context 对象更改为以下内容:

If you want your context to include the state as well as the dispatch, you need to change your initial Context object to something like this:

interface ContextType {
    state: IState,
    dispatch?: React.Dispatch<ActionType>
  }
export const Context = React.createContext<ContextType>({ state: initialState });

在调用 useContext 时,您可以删除通用的< any> .然后,您可能需要检查是否已定义 dispatch ,因为它已在上面的 ContextType 中设置为可选:

In your call to useContext, you can remove the generic <any>. Then you may need to check that dispatch is defined, since it is set in ContextType above as optional:

import AppContext, { TheProvider }  from './State'; 

// ...

const Login = () => {
  const { state, dispatch } = React.useContext(AppContext);

  const doLogin = async () => {
    if (dispatch === undefined) {
      return; // or display error message
    }
    try {
      dispatch({
        type: "setLoggedIn",
        payload: { loggedIn: false },
      });
    } catch (err) {
      console.error("failed to login with error:", err);
    }
  };

  return <div id="login"></div>; // presumably this holds your inputs, 
                                 // submit button, forgot password link, etc.
}

然后,要确保上下文正确传递,您必须确保 Login TheProvider 的子代.在同一个 Login.tsx 文件中,您可以像这样定义一个新的组件 LoginPage ,如果您有一个包含标题的 Layout 组件,页脚,CSS等:

Then, to make sure the context is properly passed down, you have to make sure Login is a child of TheProvider. In the same Login.tsx file, you could define a new component LoginPage like so, if you have a Layout component that includes your header, footer, CSS, etc:

const LoginPage = () => {
  return <TheProvider>
           <Layout>
             <h2>Please enter your information below to log in:</h2>
             <Login />
           </Layout>
         </TheProvider>
}

这篇关于离子反应类型不可分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆