iT邦幫忙

0

【已解決】【Redux/Next.js】使用redux時,有兩個slice,要怎麼整合在一起?

  • 分享至 

  • xImage

大家好,
想請問我在store資料夾中,建立一個index.tsx跟一個slices的資料夾。
資料夾裡有兩個slice,user.tsxtodolist.tsx
因為在_app.tsx中,打算只引入一個store的入口(store/index.tsx),如下

//_app.tsx
import { AppProps } from 'next/app';
import { Provider } from 'react-redux';
import  store  from '../store'; //這個 !!
import Head from 'next/head';
import '../styles/globals.css';

export default function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Provider store={store}>
      <Head>
        <title>Your Title</title>
        <meta name="description" content="Your description" />
        <link rel="icon" href="../public/icons/app/favicon.ico" />
      </Head>
      <Component {...pageProps} />
    </Provider>
  );
}

然後我的入口,store/index.tsx是長這樣

//store/index.tsx
import { configureStore } from "@reduxjs/toolkit";
import {todoReducer} from "./slices/todolist";
import {userReducer} from "./slices/user";

export default configureStore({
  reducer: {
    todo: todoReducer,
    user: userReducer
  },
});

todolist.tsx跟user.tsx分別是這樣

//todolist.tsx
import { createSlice } from "@reduxjs/toolkit";

const todoSlice = createSlice({
  name: "todo",
  initialState: {
    todolist: [
      { id: 1, name: "first todo on redux" },
      { id: 2, name: "second todo in list" },
    ],
  },
  reducers: {
    addTodo: (state, action) => {
      state.todolist.push(action.payload);
    },
  },
});
export const { actions: todoActions, reducer: todoReducer } = todoSlice;
//user.tsx
import { createSlice } from "@reduxjs/toolkit";

class Profile {
    name: string
    age: number
    email: string
    login: boolean

    constructor() {
        this.name = ''
        this.age = 0
        this.email = ''
        this.login = false
    }
}
const initialState = {
    profile: new Profile()
}

const userSlice = createSlice({
    name: 'user',
    initialState: initialState,
    reducers: {
        setLogin(state, action) {
            state.profile = new Profile()
        },
        setLogout(state) {
            state.profile = new Profile()
        }
    }
})

export const { actions: userActions, reducer: userReducer } = userSlice;

結果出現錯誤。
Error: Objects are not valid as a React child (found: object with keys {todo, user}). If you meant to render a collection of children, use an array instead.
請問是哪裡出現錯誤了呢?
感謝

-----更新--------
抱歉....
是其他component出問題....太蠢了
我在別的地方使用

import { useSelector } from 'react-redux';

const Index = () => {
    const aa = useSelector(state =>state.user.profile)
    return (
        <>
            {aa} //出錯!
        </>
    )
}
export default Index
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答