简体   繁体   中英

Context object is empty when using useState object in NextJS

I am trying to pass a context object in NextJS which is using data from a useState hook, but the state variable and setState functions are undefined when consumed. This is strange since when I pass a simple variable in its place, it works fine, it is only when using useState that it is undefined. So I know the context object is working, but the useState hook is not.

My _app.js file:

import React from 'react';
import App from 'next/app';
import Head from 'next/head';
import Aux from '../hoc/Aux';
import ContextProvider from '../context/context';

class MyApp extends App {  
  
  render() {

    const { Component, pageProps } = this.props;

    return (
      <Aux>
        <Head>
          <title>MyApp</title>
        </Head>
        <ContextProvider>
          <Component {...pageProps} />
        </ContextProvider>
      </Aux>
    );

  };

};

export default MyApp;

My context.js file:

import React, { createContext, useState } from 'react';


export const Context = createContext();

const ContextProvider = (props) => {

    const [ activeTab, setActiveTab ] = useState('OVERVIEW');

    return (    
        <Context.Provider value={{ activeTab, setActiveTab }}>      
            {props.children}    
        </Context.Provider>  
    );
};
    
export default ContextProvider;

My nav.js file:

import styled from 'styled-components';
import { Context } from '../../context/context';
import { useContext } from 'react';


const Nav = () => {

    const [activeTab, setActiveTab] = useContext(Context);

    const TourNavUl = styled.ul`
    `;

    const TourNavLi = styled.li`
    `;

    return (
        <NavUl>
            <NavLi>
                <span onClick={() => setActiveTab('OVERVIEW')}>Overview</span>
            </NavLi>
            <NavLi>
                <span onClick={() => setActiveTab('ITINERARY')}>Itinerary</span>
            </NavLi>
            <NavLi>
                <span onClick={() => setActiveTab('DETAILS')}>Details</span>
            </NavLi>
            <NavLi>
                <span onClick={() => setActiveTab('BOOKINGS')}>Bookings</span>
            </NavLi>
        </NavUl>
    );
};

export default Nav;

This is returning the error TypeError: setActiveTab is not a function , because it is undefined. As I stated earlier, if I pass a simple variable through the context it works fine so I know it is set up correctly, but the state is not passing through the context object.

What am I doing wrong with the state?

useContext is returning an object, not an array.

Instead of this

const [activeTab, setActiveTab] = useContext(Context);

Your should have this:

const {activeTab, setActiveTab} = useContext(Context);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM