下面的代码演示了我如何尝试使用 react 钩子实现 react 的上下文,这里的想法是我将能够轻松地从这样的任何子组件访问上下文
const {authState, authActions} = useContext(AuthCtx);
首先,我创建了一个导出上下文和提供程序的文件。
import * as React from 'react';
const { createContext, useState } = React;
const initialState = {
email: '',
password: ''
};
const AuthCtx = createContext(initialState);
export function AuthProvider({ children }) {
function setEmail(email: string) {
setState({...state, email});
}
function setPassword(password: string) {
setState({...state, password});
}
const [state, setState] = useState(initialState);
const actions = {
setEmail,
setPassword
};
return (
<AuthCtx.Provider value={{ authState: state, authActions: actions }}>
{children}
</AuthCtx.Provider>
);
}
export default AuthCtx;
这有效,但我在下面value
的提供程序中出现错误,可能是因为我添加了操作,因此问题是,有没有办法让我保持所有类型的输入并且仍然能够导出上下文和提供程序?
我相信我也不能createContext
放入我的主要功能中,因为它会一直重新创建它?
[ts] 输入 '{ authState: { email: string; 密码:字符串;}; authActions: { setEmail: (email: string) => void; setPassword:(密码:字符串)=> 无效;}; }' 不能分配给类型 '{ email: string; 密码:字符串;}'。对象字面量只能指定已知属性,并且类型 '{ email: string; 中不存在 'authState'。密码:字符串;}'。[2322] index.d.ts(266, 9):预期的类型来自属性“value”,该属性在此处声明为“IntrinsicAttributes & ProviderProps<{ email: string; 密码:字符串;}>' (property) authState: { email: string; 密码:字符串;}