Heim > Fragen und Antworten > Hauptteil
Ich versuche, einen Kontext-Hook für meine Anmeldeseite einzurichten. Ich verwende Typoskript. Ich habe den Kontext-Hook gestartet, habe aber Probleme mit Typdeklarationen. Wenn ich versuche, setUser zu verwenden, erscheint die folgende Fehlermeldung: Property 'setUser' existiert nicht für Typ '{}'.
Das ist bisher mein Kontext-Hook.
import { createContext, ReactNode, useEffect, useState } from "react" interface Props { children?: ReactNode } export const UserContext = createContext({}) export function UserContextProvider({children}: Props) { const [user, setUser] = useState(null) return ( <UserContext.Provider value={{user, setUser}}> {children} </UserContext.Provider> ) }
Dies ist mein Login-Code.
import { Link, Navigate } from "react-router-dom" import axios from 'axios' import { UserContext } from "../UserContext" const Login = () => { const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [redirect, setRedirect] = useState(false) **const {setUser} = useContext(UserContext)** async function handleLogin(e: any) { e.preventDefault() try { const userInfo = await axios.post('/auth/login', {email, password}) setUser(userInfo) alert('Login') setRedirect(true) } catch (e) { alert('Login failed') } } if(redirect){ return <Navigate to={'/'} /> } return ( <div> <div> <h1>Login</h1> <form onSubmit={handleLogin}> <input type="email" placeholder="your@email.com" value={email} onChange={e => setEmail(e.target.value)}/> <input type="password" placeholder="password" value={password} onChange={e => setPassword(e.target.value)}/> <button>Login</button> <div> Don't have an account? <Link to={"/auth/register"}> Sign Up</Link> </div> </form> </div> </div> ) } export default Login
P粉9981006482024-03-27 00:40:12
您需要为 UserContext
变量指定类型。因为您在 createContext
中为其指定了 {}
参数,所以 Typescript 假定上下文的类型为 React.Context<{}>
。因此,当您尝试使用上下文对象时,您会得到一个 {}
,一个空对象,它没有用户定义的属性。
首先,我将定义一个新界面,但您可以根据需要键入它。
interface IUserContext { user: any; setUser: any; //set your definitions here (please don't use `any`) }
要声明UserContext
的类型,您可以:
提供与类型匹配的默认值
export const UserContext = createContext(" ");
将默认上下文值设置为空对象/null
export const UserContext = createContext({}); export const UserContext = createContext (null);
对空对象进行类型转换(类型安全性较差)
export const UserContext = createContext({} as IUserContext);
非空断言(类型安全性较差)
export const UserContext = createContext(null!);
请注意,对于其中一些,您需要稍后编写空检查。请参阅此处了解更多信息。