Reactjs 上下文值的提供程序不';不变
我正在尝试在一个新的react+typescript示例项目中学习ContextAPI 我想管理区域设置/身份验证 我必须初始化我的上下文值(Typescript/eslint需要),特别是登录/注销函数,或者“App.tsx”中发生错误:“无法调用可能未定义的对象” 对,我试着将我的上下文初始化如下:Reactjs 上下文值的提供程序不';不变,reactjs,typescript,react-context,Reactjs,Typescript,React Context,我正在尝试在一个新的react+typescript示例项目中学习ContextAPI 我想管理区域设置/身份验证 我必须初始化我的上下文值(Typescript/eslint需要),特别是登录/注销函数,或者“App.tsx”中发生错误:“无法调用可能未定义的对象” 对,我试着将我的上下文初始化如下: const AuthContext = React.createContext<ContextProps>({ ...initialState, login: ()
const AuthContext = React.createContext<ContextProps>({
...initialState,
login: () => {
throw new Error("login() not implemented yet");
},
logout: () => {
throw new Error("logout() not implemented yet");
}
});
新的登录/注销定义似乎没有传递给AuthContext中的提供者。我很确定我错过了ContextAPI中的一个概念,并且我不理解其背后的逻辑。感谢您的建议。您需要添加具有新上下文的提供者。React将在树上查找第一个上下文提供程序,如果没有,使用者将获得默认值
const App = () => {
return (
<Context.Language.Consumer>
{({ locale, translation, switchLocale }) => (
<Context.Auth.Provider>
<Context.Auth.Consumer>
{Auth => (
<NavItem right>
{Auth.isLoggedIn ? (
<Button onClick={() => Auth.logout()}>
{translation.logout}
</Button>
) : (
<Button onClick={() => Auth.login()}>
{translation.login}
</Button>
)}
</NavItem>
)}
</Context.Auth.Consumer>
<Context.Auth.Provider>
)}
</Context.Language.Consumer>
const-App=()=>{
返回(
{({locale,translation,switchLocale})=>(
{Auth=>(
{Auth.isLoggedIn(
Auth.logout()}>
{translation.logout}
) : (
Auth.login()}>
{translation.login}
)}
)}
)}
));
};
// ./contexts/AuthContext.tsx
import React, {Component} from "react";
type ContextProps = {
isLoggedIn: boolean;
login: () => void;
logout: () => void;
};
const initialState = { isLoggedIn: false };
type Props = {};
type State = {} & typeof initialState;
const AuthContext = React.createContext<ContextProps>({
...initialState,
login: () => {
throw new Error("login() not implemented yet");
},
logout: () => {
throw new Error("logout() not implemented yet");
}
});
class AuthProvider extends Component<Props, State> {
readonly state = initialState;
login = () => {
this.setState({
isLoggedIn: true
});
};
logout = () => {
this.setState({
isLoggedIn: false
});
};
render() {
return (
<AuthContext.Provider
value={{...this.state, login: this.login, logout: this.logout}}
>
{this.props.children}
</AuthContext.Provider>
);
}
}
export const Consumer = AuthContext.Consumer;
export const Provider = AuthProvider;
// ./contexts/index.js
import * as Auth from "./AuthContext";
import * as Language from "./LanguageContext";
export { Auth, Language };
const App = () => {
return (
<Context.Language.Consumer>
{({ locale, translation, switchLocale }) => (
<Context.Auth.Provider>
<Context.Auth.Consumer>
{Auth => (
<NavItem right>
{Auth.isLoggedIn ? (
<Button onClick={() => Auth.logout()}>
{translation.logout}
</Button>
) : (
<Button onClick={() => Auth.login()}>
{translation.login}
</Button>
)}
</NavItem>
)}
</Context.Auth.Consumer>
<Context.Auth.Provider>
)}
</Context.Language.Consumer>