[英]how to access redux-toolkit state (not initial state) on Next.js environmemnt
我想在 Next.js 的 getStaticProps 中訪問 redux-toolkit 的狀態
(在商店中保存 accessToken 后,我想從 getstaticprops 訪問它需要的 api 的商店)
所以我試過這樣
export default function Page({ state }) {
console.log(state)
return <>...</>
}
export const getStaticProps = wrapper.getStaticProps((store) => {
return async () => {
const state = store.getState()
return {
props: {
state
}
}
}
})
最終訪問成功,所以我檢查了 redux devtools 上的狀態,它就在那里
但狀態實際上是初始狀態(空)
這是我在 Next.js 上的 redux 工具包設置
//_app.js
import { wrapper } from '../store'
function MyApp({ Component, pageProps }) {
axios.defaults.withCredentials = true
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}
export default wrapper.withRedux(MyApp)
/store/index.js
import { configureStore } from '@reduxjs/toolkit'
import { createWrapper } from 'next-redux-wrapper'
import logger from 'redux-logger'
import reducer from './modules'
const makeStore = (context) =>
configureStore({
reducer,
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(/*logger*/),
devTools: process.env.NODE_ENV !== 'production'
})
export const wrapper = createWrapper(makeStore, {
debug: process.env.NODE_ENV !== 'production'
})
/store/modules/index.js
import { combineReducers } from '@reduxjs/toolkit'
import { HYDRATE } from 'next-redux-wrapper'
import timer from './timer'
import user from './user'
import cart from './cart'
const reducer = (state, action) => {
if (action.type === HYDRATE) {
return {
...state,
...action.payload
}
}
return combineReducers({
user,
timer,
cart
})(state, action)
}
export default reducer
/store/modules/user.js
import { createSlice } from '@reduxjs/toolkit'
const initialState = { userInfo: null, token: null, address: null }
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
getNewToken: (state, action) => {
state.token = action.payload
},
getUserInfo: (state, action) => {
state.userInfo = action.payload
},
getAddress: (state, action) => {
state.address = action.payload
}
}
})
export const { getUserInfo, getNewToken, getAddress } = userSlice.actions
export default userSlice.reducer
getStaticProps
在服務器上運行,不知道客戶端上發生了什么。 這甚至發生在站點生成中,這可能發生在用戶實際使用頁面之前的幾秒或幾年之間。 您將永遠無法訪問那里的客戶端 Redux 存儲 - 由於您不知道客戶端如何導航到該頁面,因此它將始終處於“新”Redux 狀態。
您可以在getStaticProps
dispatch
一些操作,然后通過getState
獲取結果狀態,但每次getStaticProps
調用都會將其隔離。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.