无法读取 nextjs 中未定义的属性“dispatch”

ten*_*dli 6 reactjs react-redux next.js

我被无法读取的调度函数困住了。我想将 store.js 文件中的数据提取到 index.js 中以显示它。我目前正在为我的拥有大量数据的 Web 项目尝试 Redux。

我对 Redux 不太熟悉。有没有其他方法可以捕获海量数据?我的代码出了什么问题?

//This is the store.js file

import { createWrapper } from 'next-redux-wrapper';
import { createStore } from 'redux';
import data from './pages/API/data.json';

//initial state
const startState = {
    cards: []
};

//Actions
export const initialCards = () => {
    return {
        type: 'INITIALCARDS',
        cards: data
    }
};

export const addItem = (item) => {
    return {
        type: 'ADD',
        item
    }
};

//create a reducer

export const reducer = (state = initialState, action) => {
    switch(action.type){
        case 'INITIALCARDS':
            return {
                cards: action.cards,
            }
        case 'ADD':
            return {
                ...state,
                cards: [...state.cards, action.item],
            }
        default: return state
    }
}

//create store

const store = (initialState = startState) => {
    return createStore(reducer, initialState);
};

export const initStore = createWrapper(store);
Run Code Online (Sandbox Code Playgroud)

//This is the index.js file

import React from 'react';
import styles from './index.module.css';
import Card from './Card';
import { initStore, initialCards, addItem } from '../store';

class Index extends React.Component {
    static async getInitialProps ({ store }){
        return store.dispatch(initialCards());
    }
    render (){
        return (
            <div className={styles.app}>
                <header className={styles.header}>
                    <img src="/logo.png" className={styles.logo} alt="logo" />
                </header>
                <div className={styles.grid}>
                    {
                        this.props.cards.map((card) => (
                            <Card key={card.id} />
                        ))
                    }
                </div>
                {/*<button onClick={() => dispatch(addItem(item))}></button>*/}
            </div>
        )
    }
};

export default initStore.withRedux(Index);
Run Code Online (Sandbox Code Playgroud)

小智 6

我稍微修改了代码并得到了想要的结果。

使用 redux 中的功能组件和 useDispatch 方法。

需要进口:

import { useDispatch } from 'react-redux';
Run Code Online (Sandbox Code Playgroud)

成分:

const Index = () => {

const dispatch = useDispatch();
const {cards} = dispatch(initialCards());
return (
    <div className={styles.app}>
        <header className={styles.header}>
            <img src="/logo.png"
                className={styles.logo} alt="logo"
            />
        </header>
        <div className={styles.grid}>
        {
            cards.map((card) => (
                <Card key={card.id} />
            ))
        }
        </div>
        {/* <button onClick={() => dispatch(addItem())}></button> */}
    </div>
)};
export default initStore.withRedux(Index);
Run Code Online (Sandbox Code Playgroud)