问题描述
我正在尝试构建网站的一部分,以动态地从REST API中获取联系信息。此时,我正在使用https://jsonplaceholder.typicode.com中的示例API。
我正在尝试使用axios
,特别是useAxios
和makeUseAxios
钩子来获取API,并将其存储在应用程序上下文中,然后可以在整个站点中使用,最好使用useContext
钩子。另外,我需要能够基于用户交互来更新API调用,允许他们选择位置,进行API更新,并将其存储在应用程序的上下文中,以便所有这些动态更新。
从本质上讲,我已经基于this tutorial运行了一个基本的useContext
场景,但是我在如何存储JSON响应方面苦苦挣扎,以便可以在{{1 }}。这是到目前为止我最接近的事情:
AppContext.tsx
useContext
还有我要访问的标头组件:
import React,{ createContext,ReactNode } from 'react';
import axios from 'axios';
import { makeUseAxios } from 'axios-hooks';
import { useCookie } from 'hooks/use-cookie';
export const AppContext = createContext();
export const DealerContextProvider = ({children}: any) => {
const useAxios = makeUseAxios({
axios: axios.create({ baseURL: 'https://jsonplaceholder.typicode.com/users/' }),});
const LOCAL_STORAGE_KEY_DEALER = '_selectedDealerinformation';
const [cookie] = useCookie('one-day-location','1');
const [dealerInfo] = useAxios(`${cookie}`);
return (
<AppContext.Provider value={[dealerInfo]}>
{children}
</AppContext.Provider>
);
};
我需要的是import React,{ ReactNode,useEffect,useState,useContext } from 'react';
import { AppContext } from 'components/app-context/AppContext';
import logo from 'assets/svg/logo.svg';
import css from 'classnames';
import { Button } from 'components/button/Button';
import { Link } from 'components/link/Link';
import { NotificationBar } from '../notification-bar/NotificationBar';
import s from './Header.scss';
import { MenuIcon } from 'components/menu-icon/MenuIcon';
import { MainNav } from './navigation/MainNav';
interface HeaderProps {
navigationContent: ReactNode;
}
export const Header = ({ navigationContent }: HeaderProps) => {
const [scrolled,setScrolled] = useState(false);
const [open,setopen] = useState(false);
const blogInfo = useContext(AppContext);
const buttonLabel = blogInfo ? `${blogInfo.name}` : 'Find a Dealer';
const buttonLink = blogInfo ? `tel:${blogInfo.name}` : '/find-a-dealer';
useEffect(() => {
const handleScroll = () => {
const isScrolled = window.scrollY > 10;
if (isScrolled !== scrolled) {
setScrolled(!scrolled);
}
};
document.addEventListener('scroll',handleScroll,{ passive: true });
return () => {
document.removeEventListener('scroll',handleScroll);
};
},[scrolled]);
return (
<>
<NotificationBar notificationContent={navigationContent} />
<header
className={scrolled ? css(s.header,s.header__scrolled) : s.header}
data-open={open ? 'true' : ''}
>
<nav className={s.header__navigation}>
<ul className={s.header__container}>
<li className={s.header__logo}>
<Link to="/" className={s.header__link}>
<logo />
</Link>
</li>
<li className={s.header__primary}>
<MainNav navigationItems={navigationContent} />
</li>
<li className={s.header__utility}>
<Button href={buttonLink}>{buttonLabel}</Button>
</li>
<li className={s.header__burger}>
<MenuIcon onClick={() => setopen(!open)} />
</li>
</ul>
</nav>
</header>
</>
);
};
中的按钮来动态显示所选经销商的名称和电话号码。我可以根据需要澄清任何内容,我对React还是很陌生,仍在学习如何表达自己的全部需求。
谢谢!
解决方法
好的,在过去的24小时里,我进行了大量的挖掘工作,并且能够找到解决方案。
我有上下文,为了清楚起见,现在命名为ApiContext
。
ApiContext.tsx
import React,{ createContext } from 'react';
import axios from 'axios';
import { makeUseAxios } from 'axios-hooks';
import { useCookie } from 'hooks/use-cookie';
const contextObject = {} as any;
export const context = createContext(contextObject);
const useAxios = makeUseAxios({
axios: axios.create({ baseURL: process.env.GATSBY_API_ENDPOINT }),});
export const ApiContext = ({ children }: any) => {
const [cookie] = useCookie('one-day-location','1');
const [{ data }] = useAxios(`${cookie}`);
const { Provider } = context;
return <Provider value={data}>{children}</Provider>;
};
然后,要在各个组件之间使用它,请将AppLayout
包装在<ApiContext>
中:
AppLayout.tsx
import React,{ ReactNode } from 'react';
import { ApiContext } from 'contexts/ApiContext';
import { graphql,StaticQuery } from 'gatsby';
import { Devtools } from '../devtools/Devtools';
import { Footer } from '../footer/Footer';
import { Header } from '../header/Header';
import s from './AppLayout.scss';
interface AppLayoutProps {
children: ReactNode;
location: string;
}
const isDev = process.env.NODE_ENV === 'development';
// tslint:disable no-default-export
export default ({ children }: AppLayoutProps) => {
return (
<StaticQuery
query={`${NavQuery}`}
render={(data) => (
<>
<ApiContext>
<Header navigationContent={data.prismic.allNavigations.edges[0].node} />
<div className={s.layout}>
{children}
<Footer navigationItems={data.prismic.allNavigations.edges[0].node} />
{isDev && <Devtools />}
</div>
</ApiContext>
</>
)}
/>
);
};
const NavQuery = graphql`
query NavQuery {
prismic {
allNavigations {
edges {
node {
...NotificationBar
...NavigationItems
...FooterNavigationItems
}
}
}
}
}
`;
在我的Header
组件中,我可以使用useContext
钩子访问数据:
Header.tsx
import React,{ ReactNode,useContext,useEffect,useState } from 'react';
import Logo from 'assets/svg/logo.svg';
import css from 'classnames';
import { Button } from 'components/button/Button';
import { Link } from 'components/link/Link';
import { MenuIcon } from 'components/menu-icon/MenuIcon';
import { context } from 'contexts/ApiContext';
import { NotificationBar } from '../notification-bar/NotificationBar';
import s from './Header.scss';
import { MainNav } from './navigation/MainNav';
interface HeaderProps {
navigationContent: ReactNode;
}
export const Header = ({ navigationContent }: HeaderProps) => {
const [scrolled,setScrolled] = useState(false);
const [open,setOpen] = useState(false);
const data = useContext(context);
console.log(data);
const buttonLabel = data ? data.name : 'Find a Dealer';
const buttonLink = data ? `tel:${data.phone}` : '/find-a-dealer';
useEffect(() => {
const handleScroll = () => {
const isScrolled = window.scrollY > 10;
if (isScrolled !== scrolled) {
setScrolled(!scrolled);
}
};
document.addEventListener('scroll',handleScroll,{ passive: true });
return () => {
document.removeEventListener('scroll',handleScroll);
};
},[scrolled]);
return (
<>
<NotificationBar notificationContent={navigationContent} />
<header
className={scrolled ? css(s.header,s.header__scrolled) : s.header}
data-open={open ? 'true' : ''}
>
<nav className={s.header__navigation}>
<ul className={s.header__container}>
<li className={s.header__logo}>
<Link to="/" className={s.header__link}>
<Logo />
</Link>
</li>
<li className={s.header__primary}>
<MainNav navigationItems={navigationContent} />
</li>
<li className={s.header__utility}>
<Button href={buttonLink}>{buttonLabel}</Button>
</li>
<li className={s.header__burger}>
<MenuIcon onClick={() => setOpen(!open)} />
</li>
</ul>
</nav>
</header>
</>
);
};
我仍在进行其他优化,尤其是消除页面加载时的闪烁,并利用useCookie
(我构建的自定义钩子)在单击按钮时更新API。希望这可以使其他搜索此信息的人更加清楚,我花了几个小时才能确定解决方案。干杯。