似乎无法在React中的组件之间共享useContext或useReducer

问题描述

我想使用useContext()和useReducer()来删除redux以保存另一个包并学习一种新的状态管理方法。我遇到了障碍。

在reducer更新有效负载之后的登录页面中。在下面的屏幕截图中可以看到。我可以看到Context.Provider和reducer值已更新,但是如果我要console.log('context'),我仍然会得到初始值。

我想在组件之间共享更新的有效负载是localStorage本地执行此操作的唯一方法吗?还是我在概念上缺少某些东西。

谢谢。

Here is the Context.Provider for AuthProvider - The context is also updated but when I navigate to /dashboard or dashboard.tsx the context goes back to initialState.

useReducer state has been updated but how do I share this between login + dashboard

这是我的App.tsx

import React from 'react'
import { hot } from 'react-hot-loader/root'
import { AuthProvider } from '~context/authContext'
import { ThemeProvider } from 'styled-components'
import { StoreProvider } from 'easy-peasy'
import theme from '~styles/theme'
import { GlobalStyles } from '~styles/index'
import { Routes } from '~root/routes'
import { store } from '~store/index'

const App = () => (
  <ThemeProvider theme={theme}>
    <StoreProvider store={store}>
      <GlobalStyles />
      <AuthProvider>
        <Routes />
      </AuthProvider>
    </StoreProvider>
  </ThemeProvider>
)

export default hot(App)

这是我的AuthProvider:-

import React,{ FC,createContext,useReducer } from 'react'
import authReducer,{ authInitialState } from '~reducers/authReducer'
import { TState,IAuthProvider } from './types'

export const AuthContext = createContext<[TState,React.dispatch<any>]>(undefined)

export const AuthProvider: FC<IAuthProvider> = props => {
  const authData = useReducer(authReducer,authInitialState)
  return <AuthContext.Provider value={authData}>{props.children}</AuthContext.Provider>
}

export const AuthConsumer = AuthContext.Consumer

这是我的authReducer:-

import { IAuthInitialState,IState,IReducerAction } from './types'
import { actions } from './actions'

export const authInitialState: IAuthInitialState = {
  accesstoken: null,isAuthed: false,error: false,}

const authReducer = (state: IState,action: IReducerAction) => {
  switch (action.type) {
    case actions.SET_ACCESS_TOKEN:
      return {
        ...state,...action.payload,}
    case actions.RESET_ACCESS_TOKEN:
      return {
        ...authInitialState,}
    case actions.ERROR:
      return {
        ...authInitialState,}
    default:
      throw new Error('Unexpected action')
  }
}

export default authReducer

这是我的登录页面:-

import React,useEffect,useContext } from 'react'
import { useHistory,useLocation } from 'react-router-dom'
import { Container,Col } from 'react-bootstrap'
import { useStoreActions,useStoreState } from '~store/hooks'
import { RedirectState } from '~root/routes/privateRoute'
import { StyledRow } from './styles'
import { AuthContext } from '~context/authContext'
import { getAccesstoken } from '~utilities/index'

const Login: FC = () => {
  const history = useHistory()
  const { state } = useLocation<RedirectState>()
  const { isAuthenticated } = useStoreState(({ user }) => user)
  const [{ setusermodel },{ setSideNavModel }] = useStoreActions(({ user,sideNav }) => [user,sideNav])
  const [context,dispatch] = useContext(AuthContext)

  useEffect(() => {
    setSideNavModel({ title: 'login',activeChild: 'login' })
    const token = getAccesstoken()

    const authData = {
      isAuthed: true,accesstoken: token,time: Date(),}

    if (token) {
      dispatch({
        type: 'update',payload: authData,})

      localStorage.setItem('authedData',JSON.stringify(authData))
    }
  },[])

  return (
    <Container id="page-container">
      <StyledRow className="justify-content-md-center">
        <Col md="auto"></Col>
      </StyledRow>
    </Container>
  )
}

export default Login

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)