您好,我在下面有一个上下文提供程序文件和_app.js文件。我想要 在_app.js文件中访问AppContext。谁能帮助我,我该如何 访问_app.js文件中的AppContext。
我在_app.js文件中导入了上下文并进行了检查,但我无法获取 _app.js文件中的上下文。谁能帮助我更正此代码,并且 让我知道这里有什么问题。
import React, { createContext, useState } from 'react';
export const AppContext = createContext();
let timeout = null;
const baseURL = "api/v1/";
const headers = { 'Accept': 'application/json', "Content-type": "application/json" };
const AppContextProvider = (props) => {
const [account, setAccount] = useState();
const [alert, setAlert] = useState();
const AlertType = { success: "success", error: "error", info: "info", warning: "warning" }
const updateAccount = (objAccount) => {
setAccount(objAccount);
}
const updateAlert = (objAlert) => {
if (objAlert) {
if (objAlert.type == AlertType.success) { objAlert = { message: objAlert.message, type: objAlert.type, cssClass: "alert-teal" }; }
else if (objAlert.type == AlertType.error) { objAlert = { message: objAlert.message, type: objAlert.type, cssClass: "alert-danger" }; }
else if (objAlert.type == AlertType.warning) { objAlert = { message: objAlert.message, type: objAlert.type, cssClass: "alert-warning" }; }
else if (objAlert.type == AlertType.info) { objAlert = { message: objAlert.message, type: objAlert.type, cssClass: "alert-info" }; }
}
setAlert(objAlert);
clearTimeout(timeout);
timeout = setTimeout(() => { setAlert(); }, 8000);
}
const ExecuteAPI_Get = async (action) => {
let url = baseURL + action;
let response = await fetch(url, {
method: 'GET',
headers: headers
}).catch(err => { console.log(err); });
return await response.json();
}
const ExecuteAPI_Post = async (action, params) => {
let cookie = getCookie('Bearer');
if (cookie) { headers['Authorization'] = 'Bearer ' + cookie; }
let url = baseURL + action;
let response = await fetch(url, {
method: 'POST',
headers: headers,
body: JSON.stringify(params),
}).catch(err => { console.log(err); });
return await response.json();
}
//Cookies
const setCookie = (cname, cvalue, date) => {
var expires;
if (typeof date === "number") {
let d = new Date(); d.setTime(d.getTime() + (parseInt(date) * 24 * 60 * 60 * 1000));
expires = "expires=" + d.toUTCString();
}
else { expires = "expires=" + date.toString(); }
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
const getCookie = (cname) => {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
return (
<AppContext.Provider value={{ account, updateAccount, alert, updateAlert, ExecuteAPI_Get, ExecuteAPI_Post, setCookie, getCookie }}>
{props.children}
</AppContext.Provider>
)
}
export default AppContext;
export { AppContextProvider }
_app.js文件
import '../public/assets/css/font-awesome.min.css';
import '../public/assets/css/common.css';
import '../public/assets/css/style.css';
import Router from 'next/router';
import { AppContext, AppContextProvider } from '../components/contextprovider';
import App from "next/app";
import { PageTransition } from 'next-page-transitions';
import Layout from '../components/layout/layout';
//context not found
export default class MyApp extends App {
static contextType = AppContext;
static async getInitialProps({ Component, router, ctx }) {
let pageProps = {}
if (Component.getInitialProps) { pageProps = await Component.getInitialProps(ctx) }
return { pageProps }
}
constructor(props, context) {
super(props, context);
Router.events.off('routeChangeStart', () => { }); Router.events.off('routeChangeComplete', () => { }); Router.events.off('routeChangeError', () => { });
Router.events.on('routeChangeStart', (url) => { }); Router.events.on('routeChangeComplete', (url) => { }); Router.events.on('routeChangeError', (url) => { });
}
componentDidMount() { this.CheckLogin(); }
CheckLogin = () => {
let cookie = this.getCookie("Bearer");
if (cookie) {
//this.context.ExecuteAPI_Post('auth/me', {}).then((res) => {
// console.log(res);
// if (res && res.data) { this.context.updateAccount(res.data); }
//});
if ((Router.pathname == '/login' || Router.pathname == '/signup')) { Router.push('/'); }
}
else {
if (Router.pathname != '/signup') {
this.setCookie("Bearer", "", 0);
Router.push('/login');
}
}
}
//Temporory after get context in _app.js then remove this code and get from context
setCookie = (cname, cvalue, date) => {
var expires;
if (typeof date === "number") {
let d = new Date(); d.setTime(d.getTime() + (parseInt(date) * 24 * 60 * 60 * 1000));
expires = "expires=" + d.toUTCString();
}
else { expires = "expires=" + date.toString(); }
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
getCookie = (cname) => {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
render() {
const { Component, pageProps } = this.props;
return (
<AppContextProvider>
<Layout>
<PageTransition timeout={300} classNames="page-transition-main page-transition">
<Component {...pageProps} />
</PageTransition>
</Layout>
<style jsx global>{`
.page-transition-main{width:100%}
.page-transition-enter {opacity: 0;}
.page-transition-enter-active {opacity: 1;}
.page-transition-exit {opacity: 1;}
.page-transition-exit-active {opacity: 0;transition: opacity 300ms;}
`}</style>
</AppContextProvider>
);
}
}
答案 0 :(得分:0)
也许是这样的:
# File: app-context.ts
const AppContext = React.createContext({
user: null,
isAuthenticated: false,
setUser: null,
});
export default AppContext;
# File: _app.tsx
import AppContext from "./app-context";
export default class MyApp extends App {
render() {
const { Component, pageProps } = this.props;
return (
<AppContext.Provider
value={{
user: "todo",
isAuthenticated: false,
setUser: "todo",
}}
>
<Component {...pageProps} />
</AppContext.Provider>
);
}
}