我有一個auth-context.js如下所示的檔案:
import React, { createContext, useState } from "react";
const AuthContext = createContext({});
const AuthProvider = (props) => {
const [loggedIn, setLoggedIn] = useState(false);
const login = () => {
setLoggedIn(true);
};
const logout = () => {
setLoggedIn(false);
};
const authContextValue = {
login,
loggedIn,
logout,
};
return <AuthContext.Provider value={authContextValue} {...props} />;
};
const useAuth = () => React.useContext(AuthContext);
export { AuthProvider, useAuth };
我正在嘗試使用它來設定授權,但我無法讓它作業,因為這是一個函式,我需要在類組件中使用它。
這就是我嘗試在類組件中使用它的方式:
import { useAuth } from "../auth-context";
// the below is used when a user clicks login
const { login } = useAuth();
login();
這是我得到的錯誤:
Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
那么我該如何使用AuthContext呢?它是否需要轉換為類組件或其他東西?
這是我的index.js檔案:
ReactDOM.render(
<React.StrictMode>
<AuthProvider>
<App />
</AuthProvider>
</React.StrictMode>,
document.getElementById("root")
);
還有我的App.js檔案:
function App() {
const { loggedIn } = useAuth();
console.log("Is Logged in: " loggedIn);
return (
<Fragment>
<Router>
<HeaderComponent />
<Routes>
<Route path="/login" element={<Login />}></Route>
<Route path="/register" element={<Register />}></Route>
<Route path="/" element={<LandingPage />}></Route>
</Routes>
<FooterComponent />
</Router>
</Fragment>
);
}
export default App;
uj5u.com熱心網友回復:
選項 1 - 創建一個包裝組件的新組件Login,并使用Context.Consumer,并通過道具傳遞背景關系值:
const WrappedLogin = () => (
<AuthContext.Consumer>
{authProps => <Login {...authProps} />}
</AuthContext.Consumer>
)
在auth-context.js檔案匯出AuthContext中也是如此,因此您可以匯入它:
export { AuthProvider, useAuth, AuthContext };
選項 2 - 創建一個包裝組件的新組件Login,并用于useAuth獲取道具,并將它們傳遞給Login組件:
const WrappedLogin = () => {
const authProps = useAuth();
return <Login {...authProps} />
}
使用選項 1 和 2,您將AuthContext通過道具獲得值:
class Login extends React.Component {
render() {
const { isLoggedIn } = this.props;
}
}
選項 3 - 如果這是組件要使用的唯一背景關系,您可以使用contextType. 在這種情況下,您可以AuthContext通過以下方式使用您的值this.context:
class Login extends React.Component {
render() {
const { isLoggedIn } = this.context;
}
}
Login.contextType = AuthContext;
在auth-context.js檔案匯出AuthContext中也是如此,因此您可以匯入它:
export { AuthProvider, useAuth, AuthContext };
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/441329.html
