typescript 无法解构“useReduxContext(...)”的属性“store”,因为它为null

siotufzp  于 2023-04-22  发布在  TypeScript
关注(0)|答案(1)|浏览(162)

我正在使用NextJs 13和Redux工具包。
当我尝试npm run build命令时,我得到以下错误:无法解构“useReduxContext(...)”的属性“store”,因为它为null。
我想这和useAppSelector有关,我得到的状态正确吗?

此为页面组件:

"use client";

import React from "react";
import { useAppSelector } from "../../redux/hooks";

export default function HomePage() {
  const user = useAppSelector((state) => state.user);

  return (
    <div>
      <h1>Test</h1>
    </div>
  );
}

此为 store.ts 文件:

import { configureStore } from '@reduxjs/toolkit'
import { userSlice } from './reducers/reducers';

export const store = configureStore({
  reducer: {
    user: userSlice.reducer,
  },
})

export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

这是 hooks.ts 文件:

import { useDispatch, useSelector } from 'react-redux'
import type { TypedUseSelectorHook } from 'react-redux'
import type { RootState, AppDispatch } from './store'

export const useAppDispatch: () => AppDispatch = useDispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector

这里是 reducers.ts 文件:

import { RootState } from "./../store";
import { PayloadAction } from "@reduxjs/toolkit";
import { createSlice } from "@reduxjs/toolkit";

export interface userPayload {
  id: number,
  guest: boolean,
  username: string,
  email: string,
  income: number,
  limit: number,
}

const initialUserState = {
  id: 0,
  guest: false,
  username: "",
  email: "",
  income: 0,
  limit: 0,
};

export const userSlice = createSlice({
  name: "user",
  initialState: initialUserState,
  reducers: {
    inputData: (state, action: PayloadAction<userPayload>) => {
      (state.income = action.payload.income), (state.limit = action.payload.limit);
    },
    inputAuth: (state, action: PayloadAction<userPayload>) => {
      (state.id = action.payload.id),
        (state.guest = action.payload.guest),
        (state.username = action.payload.username),
        (state.email = action.payload.email);
    },
  },
  
});

export const { inputData, inputAuth } = userSlice.actions

export const selectCount = (state: RootState) => state.user

export default userSlice.reducer
eh57zj3b

eh57zj3b1#

我遇到了同样的问题,我的朋友。将商店提供程序移动到pages/_app.js文件中(而不是pages/index.js文件),它应该可以工作。下面是我所做的:

import { Provider } from 'react-redux';
import '../assert/css/master.scss';
import store from '../store/store';

export default function App({ Component, pageProps }) {
  return (
    <Provider store={store}>
      <Component {...pageProps} />
    </Provider>
  );
}

相关问题