Nextjs Redux 持续错误 - SyntaxError:无法在模块外部使用 import 语句

Edw*_*oto 1 reactjs redux next.js

我尝试在 Next.js 中使用 persistReducer,但我不断收到此错误

   error - SyntaxError: Cannot use import statement outside a module
    /Users/xx/node_modules/redux-persist/es/persistReducer.js:11
    import { FLUSH, PAUSE, PERSIST, PURGE, REHYDRATE, DEFAULT_VERSION } from './constants';
Run Code Online (Sandbox Code Playgroud)

这是我的 _app.tsx 文件,如下所示:

<Providers>
  <Container>
  <Component {...pageProps} />
  </Container>
</Providers>
Run Code Online (Sandbox Code Playgroud)

这是我原来的 store.ts 看起来像:

   error - SyntaxError: Cannot use import statement outside a module
    /Users/xx/node_modules/redux-persist/es/persistReducer.js:11
    import { FLUSH, PAUSE, PERSIST, PURGE, REHYDRATE, DEFAULT_VERSION } from './constants';
Run Code Online (Sandbox Code Playgroud)

这是我尝试将其更改为:

import { configureStore, Action } from "@reduxjs/toolkit"
import { useDispatch } from "react-redux"
import {
  persistStore
} from "redux-persist"
import thunk from "redux-thunk"
import rootReducer, { RootState } from "./rootReducer"

export const store = configureStore({
  reducer: rootReducer,
  middleware: [thunk]
})

export const persistor = persistStore(store)

export type AppDispatch = typeof store.dispatch

export const useAppDispatch = () => useDispatch()
Run Code Online (Sandbox Code Playgroud)

我正在使用 React 17.x、Nextjs 12.x、TypeScript 4.x、React-redux 7.2.6、Redux-persist 6.0.0

小智 5

我不小心persistStore从错误的位置导入后遇到了这个问题。检查您是否直接从 redux-persist 导入它!

import { persistStore } from "redux-persist";
Run Code Online (Sandbox Code Playgroud)