gpt4 book ai didi

javascript - 我如何在react js中访问nextjs中_app.js文件中的上下文

转载 作者:行者123 更新时间:2023-12-05 07:08:09 25 4
gpt4 key购买 nike

Hello, I have a context provider file and _app.js file below. i want access AppContext in _app.js file. can any one help me, how can i access the AppContext in _app.js file.

I have import context in _app.js file and check but i can not get context in _app.js file. can any one help me to correct this code and let me know whats the problems here.

上下文文件

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 file

              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>
);
}
}

最佳答案

您不能在放置提供者的同一位置使用上下文值。所以你可以分成两个文件:

// _app.tsx
import { ThemeProvider } from '../contexts/theme';
import Container from './_container';
import type { AppProps } from 'next/app';

function MyApp(appProps: AppProps) {
return (
<ThemeProvider>
<Container {...appProps} />
</ThemeProvider>
);
}
// _container.tsx

import type { AppProps } from 'next/app';
import { ThemeProvider as SCThemeProvider } from 'styled-components';
import { defaultColors, useTheme } from '../contexts/theme';

const Container = ({ Component, pageProps }: AppProps) => {
const { colors } = useTheme();

return (
<>
<SCThemeProvider theme={{ colors: colors ? colors : defaultColors }}>
<Component {...pageProps} />
</SCThemeProvider>
</>
);
};

export default Container;

关于javascript - 我如何在react js中访问nextjs中_app.js文件中的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61928906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com