Next.js 14 Redux 5 - TypeError:store.getState 不是函数

问题描述 投票:0回答:1

我收到此错误如何解决。我做错了什么 ? Next.js 14

enter image description here

谢谢你

>! /store/index.js
import { configureStore } from '@reduxjs/toolkit'
import cartReducer from './cartSlice';

export const makeStore = () => {
    return configureStore({
        reducer: {
            cart: cartReducer
        }
    })
}

>! /app/StoreProvider.js
"use client"
import { useRef } from 'react'
import { Provider } from 'react-redux'
import { makeStore } from '../store'
// import { cartSlice } from '../store/cartSlice'

export function StoreProvider({ children }) {
    const storeRef = useRef()
    if (!storeRef.current) {
        // Create the store instance the first time this renders
        storeRef.current = makeStore()
    }

    return <Provider store={storeRef}>{children}</Provider>
}

>! /app/layout.js
import { Inter } from "next/font/google";
import "./globals.css";

import { StoreProvider } from "./StoreProvider.js";

const inter = Inter({ subsets: ["latin"] });

export const metadata = {
    title: "Shopping App",
    description: "Test Data Pro",
};

export default function RootLayout({ children }) {
    return (
        <StoreProvider>
            <html lang="en">
                <body className={inter.className}>{children}</body>
            </html>
        </StoreProvider>
    );
}

我想使用 redux 保存我的购物车项目

但我写了以下文档https://redux.js.org/usage/nextjs

这不起作用。

reactjs next.js redux react-redux next.js14
1个回答
0
投票

代码将 React ref 作为存储值而不是 ref 的值传递,这是您要提供的实例化 Redux 存储。通过

store={storeRef.current}
而不是
store={storeRef}

export function StoreProvider({ children }) {
  const storeRef = useRef();

  if (!storeRef.current) {
    // Create the store instance the first time this renders
    storeRef.current = makeStore();
  }

  return <Provider store={storeRef.current}>{children}</Provider>;
}
© www.soinside.com 2019 - 2024. All rights reserved.