【发布时间】:2020-01-03 13:54:37
【问题描述】:
'react-redux' 中的 useSelector 函数在我的 react 应用程序中是 undefined,即使版本是最新的,并且 VS Code 中没有错误(我什至可以 ctrl-click in 并查看输入,以及node_modules 文件夹中的代码)。这体现在几个方面:
1) 以下错误[HMR] bundle has 1 warnings: export 'useSelector' was not found in 'react-redux'。
2) 在以下组件中:
import React, { useState } from 'react';
import { useSelector } from 'react-redux'; // importing useSelector does not error in VS Code
const TestComponent = () => {
const [x, setX] = useState("hello"); // useState works correctly
console.log(useSelector); // but useSelector is undefined when the application runs
return <p> {x} </p>
}
export default TestComponent;
我不确定这个错误是否与热重载、webpack 或其他完全有关。
软件包版本:
// react
"@types/react": "^16.9.9",
"react": "^16.10.2",
// redux
"@types/react-redux": "^7.1.5"
"react-redux": "^7.1.3",
"redux": "^4.0.5",
我的尝试:
1) 将所有 redux 包更新到最新版本
2) 删除node_modules并重新安装
3) 将热重载包更新到最新版本
4) 查看node_modules 中react-redux 的代码,它确实有useSelector 钩子,但如果我执行以下操作:import * as ReactRedux from 'react-redux'; 然后console.log(ReactRedux),我看到以下内容,表示没有的钩子已被导入:
【问题讨论】:
-
你连接组件了吗?尝试更新您的默认导出默认连接()测试组件;并导入连接方法 import { connect, useSelector } from 'react-redux';
-
@DILEEPTHOMAS 我正在使用钩子,这意味着您不需要连接组件。还是谢谢
-
通常 useSelector 返回一个函数而不使用 connect 我已经添加了一个示例应用程序请检查
标签: reactjs typescript redux react-redux