簡體   English   中英

將 react redux 與 next.js 結合使用

[英]Using react redux with next.js

我嘗試將 Redux 與next.js 啟動項目一起使用,並且我在該項目上安裝了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));
    }
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM