[英]Authentication with Next.js and Redux
這是我的情況。 我正在嘗試在加載時對用戶進行身份驗證,並且需要在pages/_app.js
文件中運行身份驗證。 這是錯誤useReduxContext.js:24 Uncaught Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>
useReduxContext.js:24 Uncaught Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>
中。 有沒有辦法在包裝的<Provider>
中運行身份驗證。 這是codesandbox的 鏈接
文件頁面/_app.js
import React, { useEffect } from 'react';
import { Provider, useDispatch } from 'react-redux';
import { auth } from '../lib/firebase.js';
import { getUserLoggedIn } from '../store/user.js';
import configureAppStore from '../store/configureAppStore.js';
import Header from '../components/nav/Header.jsx';
const store = configureAppStore();
function MyApp({ Component, pageProps }) {
const dispatch = useDispatch();
// to check firebase auth state
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(async (user) => {
if (user) {
const idTokenResult = await user.getIdTokenResult();
dispatch(
getUserLoggedIn({
email: user.email,
token: idTokenResult.token,
})
);
}
});
// cleanup
return () => unsubscribe();
}, []);
return (
<>
<Provider store={store}>
<Header />
<Component {...pageProps} />
</Provider>
</>
);
}
export default MyApp;
這個問題的一個簡單解決方案是創建一個空組件,在 useEffect 中為您運行身份驗證。
import React, { useEffect } from 'react';
import { Provider, useDispatch } from 'react-redux';
import { auth } from '../lib/firebase.js';
import { getUserLoggedIn } from '../store/user.js';
import configureAppStore from '../store/configureAppStore.js';
import Header from '../components/nav/Header.jsx';
const store = configureAppStore();
function MyApp({ Component, pageProps }) {
const AuthComponent = React.memo(() => {
const dispatch = useDispatch();
// to check firebase auth state
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(async (user) => {
if (user) {
const idTokenResult = await user.getIdTokenResult();
dispatch(
getUserLoggedIn({
email: user.email,
token: idTokenResult.token,
})
);
}
});
// cleanup
return () => unsubscribe();
}, []);
return null;
})
return (
<>
<Provider store={store}>
<AuthComponent />
<Header />
<Component {...pageProps}
/>
</Provider>
</>
);
}
export default MyApp;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.