当尝试运行我的React应用程序时,我在浏览器控制台中得到以下错误:Uncaught TypeError: useSelector不是一个函数。代码在VS code上可以正常编译
下面是导致问题的App.js代码:
const BrowserRouter = require('react-router-dom');
const Navigate = require('react-router-dom');
const Routes = require ('react-router-dom');
const Route = require ('react-router-dom');
const HomePage = require ('scenes/homePage');
const LoginPage = require ('scenes/loginPage');
const ProfilePage = require ('scenes/ProfilePage');
const useMemo = require ('react');
const useSelector = require ('react-redux');
const CssBaseline = require ('@mui/material');
const ThemeProvider = require ('@mui/material');
const createTheme = require ('@mui/material/styles');
const themeSettings = require ('./theme');
function App() {
const mode = useSelector((state) => state.mode);
const theme = useMemo(() => createTheme(themeSettings(mode)), [mode]);
const isAuth = Boolean(useSelector((state) => state.token));
return (
<div className="app">
<BrowserRouter>
<ThemeProvider theme={theme}>
<CssBaseline />
<Routes>
<Route path="/" element={<LoginPage />} />
<Route
path="/home"
element={isAuth ? <HomePage /> : <Navigate to="/" />}
/>
<Route
path="/profile/:userId"
element={isAuth ? <ProfilePage /> : <Navigate to="/" />}
/>
</Routes>
</ThemeProvider>
</BrowserRouter>
</div>
);
}
export default App;
任何帮助都会很感激。由于
我首先看了看以前的线程,并尝试如下:
- 我仔细检查了一下,我正确地导入了useSelector,使用:const useSelector = require ('react-redux');
- 我还检查了我的react-redux是最新版本。
- 我还检查了react-redux文档,以确保语法正确,它似乎不是一个语法错误
useSelector
不是react-redux
的默认导出,它是命名的导出。
const { useSelector } = require('react-redux');
或者你可能需要使用:
const ReactRedux = require('react-redux');
...
ReactRedux.useSelector((state) => state.token);
或者只使用常规导入
import { useSelector } from 'react-redux';