【问题标题】:Receive new props in _app.js (nextjs)?在 _app.js (nextjs) 中接收新道具?
【发布时间】:2020-05-13 18:11:56
【问题描述】:

我想说,如果我在 _app 的 componentDidMount 中调度一个动作,我能在 _app 中收到这个动作的新道具吗?如果是,如何?谢谢

import React from 'react'
import {Provider} from 'react-redux'
import App, {Container} from 'next/app'
import withRedux from 'next-redux-wrapper'
import withReduxSaga from 'next-redux-saga'
import configureStore from './configure-store'

class ExampleApp extends App {
  static async getInitialProps({Component, ctx}) {
    let pageProps = {}
     //This a action with redux-saga
     ctx.store.dispatch(doSomething)

    if (Component.getInitialProps) {
      pageProps = 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(configureStore)(withReduxSaga(ExampleApp))

在这段代码中,我如何以及在哪里可以恢复我的操作结果?

我的 configureStore :

import reducers from "./services/reducers";
import { createStore, applyMiddleware, compose } from "redux";
import createSagaMiddleware from "redux-saga";
import IndexSaga from "./services/sagas";

export const configureStore = (preloadedState, { isServer, req = null }) => {
  const composeEnhancers =
    (typeof window !== "undefined" &&
      window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) ||
    compose;
  const sagaMiddleware = createSagaMiddleware();

  const store = createStore(
    reducers,
    preloadedState,
    composeEnhancers(applyMiddleware(sagaMiddleware))
  );

  if (req || !isServer) {
    store.sagaTask = sagaMiddleware.run(IndexSaga);
  }
  return store;
};

【问题讨论】:

  • 这是redux的主要概念。请阅读文档。
  • 我知道redux,但我学习nextjs,我想使用redux,它的工作方式不同......
  • 概念相同。您发送一个动作,将结果存储在 store 中,然后从 store 中获取。
  • 我想,你不知道你在说什么。你知道nextjs吗?你知道它是如何工作的吗?
  • 是的,我知道我在说什么。 Redux 与任何框架都不相关!只需检查next-redux-wrapper

标签: reactjs next.js


【解决方案1】:

然后回到你的商店并从那里带来一些更新的价值。

....
const store = configureStore.getState();

【讨论】:

  • 感谢您的帮助,我的应用程序使用类组件。我不会用钩子哈哈。
  • SSR 仅用于渲染初始状态,在第一次渲染后我们有一个普通的客户端 redux 应用程序。
  • 您已经在const {Component, pageProps, store} = this.props 中拥有您的商店。 store 变量应包含更新后的 store。
猜你喜欢
  • 2022-07-19
  • 2021-11-03
  • 2021-03-18
  • 2020-03-12
  • 2019-07-20
  • 1970-01-01
  • 2022-01-24
  • 2017-05-25
  • 2021-12-04
相关资源
最近更新 更多