繁体   English   中英

反应上下文返回未定义

[英]React context is returning undefined

不知道为什么会这样,我已经检查以确保状态值不是未定义的,它不是,我看不出我哪里出错了。

我的 authContext.js 文件

const initialState = {
  isAuthorized: false,
}

export const authContext = React.createContext() 

export default function AuthContextComp(props) {
  const [state, dispatch] = useReducer(reducer,initialState)

  return (
    <authContext.Provider authState={state}>
      {props.children}
    </authContext.Provider>
  )
}

function reducer(state, action){
  switch (action.type) {
    case 'signIn':
      return true;
      break;
  
    default:
      return state;
  }
}

我的应用文件

function MyApp({ Component, pageProps, appProps }) {

  return (
    <GlobalContextWrapper pageData={pageProps}>
      <AuthContextWrapper>
        <div style={{textAlign:'center',paddingTop: 200}}>
          <h2>Signed in</h2>
          <button>Log in or log out</button>
          <Component {...pageProps} />
          <Test/>
        </div>
      </AuthContextWrapper>
    </GlobalContextWrapper>
  );
}

export default MyApp;

我试图使用上下文的组件

import React, {useContext} from 'react'
import {authContext} from '../global/authContext/AuthContext'

export default function Test() {
  const t = useContext(authContext)
  return (
    <div>
       This is the test component
    </div>
  )
}

你能看出这里有什么不对吗? 我正在使用 next.js 我不知道为什么不

问题是当将 state 传递给提供时,名称应该是值。 不知道为什么会这样

    <authContext.Provider  value={state}>
      {props.children}
    </authContext.Provider>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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