将 React redux 与 next.js 结合使用

Using react redux with next.js

我尝试将 Redux 与 next.js starter 项目一起使用,并且我在该项目上安装了 next-redux-wrapper,但我不确定该项目的根文件在哪里。

我尝试按照 next-redux-wrapper 上显示的教程进行操作,但没有成功。没有任何变化。

请帮助我如何将 Redux 添加到项目中。

此致。

Next.js使用App组件初始化页面。您可以覆盖它并控制页面初始化。

尽管此演示是针对 next.js 的,但它应该适用于 nextjs-starter。

安装 next-redux-wrapper:

npm install --save next-redux-wrapper

添加_app.js文件到./pages目录:

// pages/_app.js
import React from "react";
import {createStore} from "redux";
import {Provider} from "react-redux";
import App, {Container} from "next/app";
import withRedux from "next-redux-wrapper";

const reducer = (state = {foo: ''}, action) => {
    switch (action.type) {
        case 'FOO':
            return {...state, foo: action.payload};
        default:
            return state
    }
};

/**
* @param {object} initialState
* @param {boolean} options.isServer indicates whether it is a server side or client side
* @param {Request} options.req NodeJS Request object (not set when client applies initialState from server)
* @param {Request} options.res NodeJS Request object (not set when client applies initialState from server)
* @param {boolean} options.debug User-defined debug mode param
* @param {string} options.storeKey This key will be used to preserve store in global namespace for safe HMR 
*/
const makeStore = (initialState, options) => {
    return createStore(reducer, initialState);
};

class MyApp extends App {

    static async getInitialProps({Component, ctx}) {

        // we can dispatch from here too
        ctx.store.dispatch({type: 'FOO', payload: 'foo'});

        const pageProps = Component.getInitialProps ? await Component.getInitialProps(ctx) : {};

        return {pageProps};

    }

    render() {
        const {Component, pageProps, store} = this.props;
        return (
            <Container>
                <Provider store={store}>
                    <Component {...pageProps} />
                </Provider>
            </Container>
        );
    }

}

export default withRedux(makeStore)(MyApp);

然后,实际的页面组件可以简单地连接起来: 此演示如何在页面中连接 index.js

import Link from "next/link";
import React from "react";
import {
  Container,
  Row,
  Col,
  Button,
  Jumbotron,
  ListGroup,
  ListGroupItem
} from "reactstrap";
import Page from "../components/page";
import Layout from "../components/layout";

import { connect } from "react-redux";

class Default extends Page {
  static getInitialProps({ store, isServer, pathname, query }) {
    store.dispatch({ type: "FOO", payload: "foo" }); // component will be able to read from store's state when rendered
    return { custom: "custom" }; // you can pass some custom props to component from here
  }
  render() {
    return (
      <Layout>content...</Layout>
    );
  }
}

export default connect()(Default);

有关详细信息,请参阅文档:next-redux-wrapper

首先,我使用“npx create-next-app”

创建了简单的 next.js 应用

然后我在名为“store”的文件夹中创建了通用的 redux 设置。

这是文件夹结构

我在页面中创建了一个 _app.js。里面的代码是这样的——

如果有人需要任何设置方面的帮助,请告诉我...

这个问题需要更新:

"next": "12.1.4",
"next-redux-wrapper": "^7.0.5",
"redux-devtools-extension": "^2.13.9",
"redux-thunk": "^2.4.1"

创建商店

import { createStore, applyMiddleware } from "redux";
import { HYDRATE, createWrapper } from "next-redux-wrapper";
import reducers from "./reducers/reducers";

import thunkMiddleware from "redux-thunk";

// middleware is an array
const bindMiddleware = (middleware) => {
  if (process.env.NODE_ENV !== "production") {
    const { composeWithDevTools } = require("redux-devtools-extension");
    return composeWithDevTools(applyMiddleware(...middleware));
  }
  return applyMiddleware(...middleware);
};
// this is main reducer to handle the hydration
const reducer = (state, action) => {
  // hydration is a process of filling an object with some data
  // this is called when server side request happens
  if (action.type === HYDRATE) {
    const nextState = {
      ...state,
      ...action.payload,
    };
    return nextState;
  } else {
    // whenever we deal with static rendering or client side rendering, this will be the case
    // reducers is the combinedReducers
    return reducers(state, action);
  }
};

const initStore = () => {
  return createStore(reducer, bindMiddleware([thunkMiddleware]));
};

export const wrapper = createWrapper(initStore);

_app.js

import { wrapper } from "../redux/store";

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

export default wrapper.withRedux(MyApp);

与 getServerSideProps 一起使用

// sample action
import { getRooms } from "../redux/actions/roomActions";
import { wrapper } from "../redux/store";

export const getServerSideProps = wrapper.getServerSideProps(
  (store) =>
    // destructuring context obj
    async ({ req, query }) => {
      await store.dispatch(getRooms(req, query.page));
    }
);