React-Redux使用useSelector报错:找不到Redux上下文值
问题原因及解决方案
问题原因
你在App组件中直接调用useSelector,但App组件本身并没有被<Provider>包裹——<Provider>是App组件返回内容的一部分,此时执行useSelector时,Redux的上下文还未建立,自然会抛出找不到context value的错误。其他文件能正常使用,是因为它们都是<Provider>的子组件,处于Redux上下文范围内。
解决方案
把需要使用useSelector的逻辑移到<Provider>内部的子组件中,比如拆分一个专门处理导航判断的组件:
修改后的代码示例
import { ApolloClient, ApolloProvider } from "@apollo/client"; import { Provider, useSelector } from "react-redux"; import Navigation from "./navigation"; import Navigation2 from "./navigation2"; import { store } from "./src/Redux/store"; import InMemoryCacheFct from "./src/apolloClient/InMemoryCache"; // 拆分出内部组件,在Provider范围内使用useSelector const AuthNavigation = () => { const user = useSelector(state => state.auth.isAuthenticated); return user ? <Navigation /> : <Navigation2 />; }; export default function App() { const client = new ApolloClient({ uri: ".......serverUrl", cache: InMemoryCacheFct(), queryDeduplication: true, }); return ( <ApolloProvider client={client}> <Provider store={store}> <AuthNavigation /> </Provider> </ApolloProvider> ); }
或者也可以将App组件拆分为外层和内层,外层负责包裹Provider,内层处理业务逻辑:
import { ApolloClient, ApolloProvider } from "@apollo/client"; import { Provider, useSelector } from "react-redux"; import Navigation from "./navigation"; import Navigation2 from "./navigation2"; import { store } from "./src/Redux/store"; import InMemoryCacheFct from "./src/apolloClient/InMemoryCache"; // 内层组件,处于Provider上下文内 const AppContent = () => { const user = useSelector(state => state.auth.isAuthenticated); const client = new ApolloClient({ uri: ".......serverUrl", cache: InMemoryCacheFct(), queryDeduplication: true, }); return ( <ApolloProvider client={client}> {user ? <Navigation /> : <Navigation2 />} </ApolloProvider> ); }; // 外层组件负责包裹Provider export default function App() { return ( <Provider store={store}> <AppContent /> </Provider> ); }
内容的提问来源于stack exchange,提问作者med hedi ben salah
相关产品推荐
相关产品推荐

