I created a store and authreducer and every thing works as expected
but when I add the useSelector in app.js I get this error:

错误错误:找不到react-redux上下文值;请确保 该组件包裹在<Provider>

(我曾try 在其他文件中使用useSelector,没有任何错误.)

enter image description here

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";

export default function App() {
  // the err is when I add this line even he works in other files
  const user = useSelector(state => state.auth.isAuthenticated);

  const client = new ApolloClient({
    uri: ".......serverUrl",
    cache: InMemoryCacheFct(),
    queryDeduplication: true,
  });

  return (
    <ApolloProvider client={client}>
      <Provider store={store}>
        {user ? <Navigation /> : <Navigation2 />}
      </Provider>
    </ApolloProvider>
  );
}

推荐答案

除非您所在的组件是树中redux提供者below,否则您无法使用useSelector.

您可以这样做:

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";

export default function App() {

  const client = new ApolloClient({
    uri: ".......serverUrl",
    cache: InMemoryCacheFct(),
    queryDeduplication: true,
  });

  return (
    <ApolloProvider client={client}>
      <Provider store={store}>
        <Root />
      </Provider>
    </ApolloProvider>
  );
}

function Root() {
  const user = useSelector(state => state.auth.isAuthenticated);
  return user ? <Navigation /> : <Navigation2 />
}

你可以阅读react context here

Javascript相关问答推荐

我的YouTube视频没有以html形式显示,以获取免费加密信号

橡皮擦完全让画布变成白色

如何保持子画布元素的1:1宽高比?

如何访问react路由v6加载器函数中的查询参数/搜索参数

我的glb文件没有加载到我的three.js文件中

有什么(最佳)方法可以从模块中获取脚本模块的多姆元素吗?

深嵌套的ng-container元素仍然可以在Angular 布局组件中正确渲染内容吗?

如何从调整大小/zoom 的SVG路径定义新的d属性?""

查找最长的子序列-无法重置数组

当id匹配时对属性值求和并使用JavaScript返回结果

将内容大小设置为剩余可用空间,但如果需要,可在div上显示滚动条

用于在路径之间移动图像的查询

查询参数未在我的Next.js应用路由接口中定义

当我在Reaction中创建一个输入列表时,我的输入行为异常

为什么可选参数的顺序会导致问题?

我想将Sitecore搜索面过滤器从多个转换为单个

为什么当我更新数据库时,我的所有组件都重新呈现?

使用类型:assets资源 /资源&时,webpack的配置对象&无效

处理TypeScrip Vue组件未初始化的react 对象

我们是否可以在reactjs中创建多个同名的路由