【问题标题】:How to use Redux devtools with Nextjs?如何将 Redux devtools 与 Nextjs 一起使用?
【发布时间】:2021-09-15 08:01:05
【问题描述】:

我正在尝试在我的 Next.js 应用程序上使用 Redux DevTools 扩展。 redux 工作正常,但我无法在 devtools 中看到状态。

我做错了什么,我该如何解决?

_app.js



function MyApp({ Component, pageProps }) {
  const store = useStore(pageProps.initialReduxState);

  return (
    <Provider store={store}>
      <Component {...pageProps} />
    </Provider>
  )
}

let store;

function initStore(initialState) {
    const composeEnhancers = typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

  return createStore(
    reducers,
    initialState,
    composeEnhancers(
        applyMiddleware(thunkMiddleware)
    )
  )
}

function useStore(initialState) {
  const store = useMemo(() => initializeStore(initialState), [initialState])
  return store
}

const initializeStore = (preloadedState) => {
  let _store = store ?? initStore(preloadedState)

  if (preloadedState && store) {
    _store = initStore({
      ...store.getState(),
      ...preloadedState,
    })
    store = undefined
  }

  if (typeof window === 'undefined') return _store
  if (!store) store = _store

  return _store
}

【问题讨论】:

    标签: reactjs redux react-redux next.js redux-thunk


    【解决方案1】:

    我正在使用 next-redux 包装器,这是我设置它的方式:

    const bindMiddleware = (middleware) => {
      if (process.env.NODE_ENV !== "production") {
       // I require this only in dev environment
        const { composeWithDevTools } = require("redux-devtools-extension");
        return composeWithDevTools(applyMiddleware(...middleware));
      }
      return applyMiddleware(...middleware);
    };
    
    export const makeStore = (context) => {
      const store = createStore(
        rootReducer,
        bindMiddleware([thunk])
      );
      return store;
    };
    

    【讨论】:

      【解决方案2】:

      问题在于 devtools 只在浏览器中运行,因为 nextjs 是一个框架,它在浏览器之前在节点中执行 javascript。

      解决方案?将条件 if (typeof window !== 'undefined') 添加到 composeEnhancers 部分。我在我的代码中做了这样的事情:

      // ---Redux DevTools
      let composeEnhancers = compose;
      if (typeof window !== 'undefined') {
        composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
      }
      

      这可确保您的 redux devtools 配置仅在浏览器中运行:D

      【讨论】:

      • 如果您仔细阅读问题,您会发现您的建议已包含在共享代码中。
      • 嘿史蒂文。这个答案很有效,非常感谢你拯救了我的一天
      【解决方案3】:

      使用ternary operator

      =>

      const store = createStore(   todoReducer,   typeof window !== "undefined"
          ? window.__REDUX_DEVTOOLS_EXTENSION__ &&
              window.__REDUX_DEVTOOLS_EXTENSION__()
          : null ); 
      

      【讨论】:

        猜你喜欢
        • 2019-02-06
        • 2016-09-27
        • 2020-08-17
        • 2023-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-14
        相关资源
        最近更新 更多