简体   繁体   English

使用私有路由后 AuthContext 组件出现问题

[英]Trouble with the AuthContext component after using a private route with it

I was following this tutorial regarding Firebase authentication components.我正在关注有关 Firebase 身份验证组件的本教程 Ran into this issue after adding a private route within an Auth Context component:在 Auth Context 组件中添加私有路由后遇到此问题: 错误 #1

Console shows other errors alongside this:控制台显示其他错误:
#2: #2: 错误 #2

#3: #3: 错误 #3

Auth Context Component:身份验证上下文组件:

export const AuthContext = createContext(null);
export const useAuth = () => useContext(AuthContext);

export const AuthProvider = ({ children }) => {
let [currentUser, setCurrentUser] = useState();
const [loadedCredentials, loadingCredentials] = useState(false);

//Other Processes

const loginProcess = (email, password) => {
    return firebase
        .auth()
        .signInWithEmailAndPassword(email, password);
};

//Other Processes

useEffect(() => {
    return firebase.auth().onAuthStateChanged(user => {
        setCurrentUser(user);
        loadingCredentials(true);
    });
}, []);

//Other Processes

return (
    <AuthContext.Provider
        value={ { currentUser, loginProcess } }
        >
        { loadedCredentials && children }
    </AuthContext.Provider>
);}

Private Route Component:私有路由组件:

export default function PrivateRoute({ component: Component, ...rest }) {
 
const { currentUser } = useAuth();
return (
    <Route
        {...rest}
        render={props => {
            return currentUser ? <Component {...props} /> : <Redirect to="/login" />
        }}
    ></Route>
);}

The Login Component:登录组件:

const LogIn = () => {
const [loginStatus, updateStatus] = useState(null);
const { loginProcess } = useAuth();
const history = useHistory();

const loginForm = useFormik({
    //Form values,
    onSubmit: (values) => { loginSubmission(values) }
});

const loginSubmission = (values) => {
    loginProcess(values.email, values.password)
        .then( () => { history.push("/dashboard"); } )
        .catch( (error) => {
            //Error Reporting
        });
};

The App Component:应用组件:

    const App = () => {
    return (
    <Router>
        <AuthProvider>

        <MainHeader />
        <Switch>

            <Route exact path="/signup">
                    <SignUp />
            </Route>

            <PrivateRoute exact path="/dashboard" component={ <Dashboard /> } />
            //Other Routes

One initial solution that seemed tangentially viable suggested a somewhat different way of writing the exports.似乎一个初始解切线可行的建议写出口的有些不同的方式。 Made the change, but it didn't work.进行了更改,但没有奏效。 Assumed that the error came from use of the useHistory Hook in the Login component, though the train of thought went nowhere when it was put to work.假设错误来自在 Login 组件中使用 useHistory Hook,尽管当它投入工作时,思路无处可去。 Ran out of options and feel a bit desperate about clearing this problem.用尽了选择,对解决这个问题感到有点绝望。

try changing the following line:尝试更改以下行:

<PrivateRoute exact path="/dashboard" component={Dashboard} />

Here is an example of auth context using your code provided:以下是使用您提供的代码的身份验证上下文示例:

import { useEffect, useState, createContext } from 'react'
import app from '../utils/firebase'

export const AppContext = createContext()

export const AppProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null)
  const [authState, setAuthState] = useState(false)

  const loginProcess = (email, password) => {
    return app.auth().signInWithEmailAndPassword(email, password)
  }

  useEffect(() => {
    console.log('state unknown')
    setAuthState(false)
    return app.auth().onAuthStateChanged(user => {
      setCurrentUser(user)
      setAuthState(true)
    })
  }, [currentUser])

  return (
    <AppContext.Provider value={{ currentUser, authState, loginProcess }}>
      {authState && children}
    </AppContext.Provider>
  )
}

export const useProvider = () => useContext(AppContext)

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

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