如何在Nextjs布局中使用上下文挂钩

时间:2020-06-09 17:18:42

标签: reactjs react-hooks next.js use-context

我正在使用NextJS构建应用程序。我的应用程序显示帖子列表,用户可以按A-Z或Z-A排序列表,并每页显示特定数量的帖子(10、20等)。当用户单击某个帖子以访问该特定的帖子页面,然后返回主列表时,排序和分页首选项被重置,我设法使用Cookie保留了保留的值,但是我想使用{{ 1}}。 对于这个应用程序,我有一个useContext()文件,并认为这是插入我的Layout.js的正确位置,如下所示:

Provider

但是当我尝试从其中一页获取价值时,我得到了import React, {useState} from 'react'; import Navbar from './Navbar'; import Head from 'next/head'; import {SortingContext} from './UseContext'; const Layout = (props)=> { const [value, setValue] = useState('hello'); return (<SortingContext.Provider value={{value, setValue}}> <div> <Head> <title>MyApp</title> </Head> <Navbar/> {props.children} </div> </SortingContext.Provider> )};

我在应用程序的其他地方使用了TypeError: Cannot read property 'value' of null,所以我知道我可以使用它。我只是不知道将其放在NextJS应用程序中的什么位置,因此即使我访问了其他页面,该值也将保持不变。

这是我尝试打印值的index.js:

useContext

还有我的UseContext.js:

import React, { useState, useEffect, useContext } from 'react';
import withData from '../lib/apollo';
import Layout from '../components/Layout';
import {SortingContext} from '../components/UseContext';
import Footer from '../components/Footer';

const Home = () => {

  const {value, setValue} = useContext(SortingContext);

  return (
    <Layout>
      <div className='main_screen'>
  <h1>{value}</h1>
      </div>
      {siteOptions && <Footer />}
    </Layout>
  )
};

export default withData(Home);

1 个答案:

答案 0 :(得分:0)

问题是您正在尝试useContext在提供上下文的树中更高的位置。现在,您是Layout中的提供者,但是,您正在尝试在布局的父级Home中使用它。因此,您可以做几件事,可以将提供程序移到Home之外的更高位置,或者如果要保留当前的结构,可以执行以下操作:

const Home = () => {

  const {value, setValue} = useContext(SortingContext);

  return (
    <Layout>
      <SortingContext.Consumer>
         {value =>
            <div className='main_screen'>
              <h1>{value}</h1>
            </div>
            {siteOptions && <Footer />}
         }
      </SortingContext.Consumer>
    </Layout>
  )
};

但是,我的建议可能是将其上移,您可以在应用程序级别使用它。