[英]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.