找不到反应冗余上下文值;请确保组件已包装在 即使<Provider>已包装在提供程序中



我正试图在根文件(App.js(中的firebase中获取当前用户的UID,但我遇到了一个关于react redux的问题,尽管我封装了Provider并设置了存储。顺便说一下,我正在使用redux工具包。我在这里错过了什么?谢谢你的回答。

下面是我的App.js

import { StrictMode, useEffect } from 'react'
import { Provider } from 'react-redux';
import { useDispatch } from 'react-redux';
import { getCurrentUser } from 'store/slices/authSlice';
import store from 'store';
import routes from 'routes/routes';
import PrivateRoute from 'routes/PrivateRoutes';
const App = () => {
const dispatch = useDispatch();
useEffect(() => {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user;
console.log(uid);
dispatch(getCurrentUser(uid))
} else {
// User is signed out
// ...
}
});
}, [dispatch]);
return (
<StrictMode>
<Provider store={store}>
<Router>
<Switch>
{routes.map((route, i) => (
route.auth ? (
<PrivateRoute
key={i}
exact
path={route.path}
component={route.component}
/>
) : (
<Route
key={i}
exact
path={route.path}
component={route.component}
/>
)
))}
</Switch>
</Router>
</Provider>
</StrictMode>
);
}
export default App;

App必须包装在提供程序中,因为您在其中使用useDispatch。现在它只是一个子级。Provider设置上下文,以便只有它的子级可以访问它,而不是父级。

尝试:

import { StrictMode, useEffect } from 'react'
import { Provider } from 'react-redux';
import { useDispatch } from 'react-redux';
import { getCurrentUser } from 'store/slices/authSlice';
import store from 'store';
import routes from 'routes/routes';
import PrivateRoute from 'routes/PrivateRoutes';
const AppWrapper = () => {
const store = createStore(rootReducer);
return (
<Provider store={store}> // Set context
<App /> // Now App has access to context
</Provider>
)
}
const App = () => {
const dispatch = useDispatch();
useEffect(() => {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user;
console.log(uid);
dispatch(getCurrentUser(uid))
} else {
// User is signed out
// ...
}
});
}, [dispatch]);
return (
<StrictMode>
<Provider store={store}>
<Router>
<Switch>
{routes.map((route, i) => (
route.auth ? (
<PrivateRoute
key={i}
exact
path={route.path}
component={route.component}
/>
) : (
<Route
key={i}
exact
path={route.path}
component={route.component}
/>
)
))}
</Switch>
</Router>
</Provider>
</StrictMode>
);
}
export default App;

问题是您正试图在主组件中使用useDispatch,而该组件没有用Provider封装。你应该创建一个导航器或路由器组件,并在一个中完成

相关内容

  • 没有找到相关文章

最新更新