本质上,我试图在用户登录后在next.js应用中保留用户,即,在刷新任何浏览器后,它都会保留数据/状态。
使用redux时,一种方法是使用redux-persist!
这些是版本:
"next": "^9.0.5",
"redux-persist": "^6.0.0",
"redux": "^4.0.4",
这是我的pages/index.js
文件。
import { connect } from 'react-redux'
import Head from '../components/head'
import HomeLayout from '../components/Home/Home.jsx'
import 'semantic-ui-css/semantic.min.css'
import '../styles/styles.scss'
import {bindActionCreators} from 'redux'
import { logInUser } from '../store/index'
class Home extends React.Component {
static getInitialProps ({ isLoggedIn }) {
return {isLoggedIn}
}
componentDidMount() {
logInUser()
}
render() {
const { isLoggedIn } = this.props
console.log("isLoggedIn ", isLoggedIn)
return (
<div>
<Head title = 'Home' />
<HomeLayout isLoggedIn = { isLoggedIn }/>
</div>
)
}
}
const mapDispatchToProps = { logInUser }
export default connect(state =>
state,
mapDispatchToProps,
)(Home)
这是我的商店
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import { persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web
import { createLogger } from 'redux-logger'
import thunkMiddleware from 'redux-thunk';
/* initial state */
var startState = { isLoggedIn: false }
/* action types */
export const actionTypes = {
IS_LOGGED_IN: 'IS_LOGGED_IN'
}
/* reducer(s) */
export const reducer = (state = initialState, action) => {
switch (action.type) {
case 'IS_LOGGED_IN':
return Object.assign({}, state, {
isLoggedIn: action.isLoggedIn
})
default:
return state
}
};
/* actions */
export const logInUser = () => {
return { type: actionTypes.IS_LOGGED_IN, isLoggedIn: true, }
}
const persistConfig = {
key: 'root',
storage,
// whitelist: ['exampleData'] // place to select which state you want to persist
}
const persistedReducer = persistReducer(persistConfig, reducer)
// create a store
export const initializeStore = (initialState = startState) => {
return createStore(
persistedReducer,
initialState,
composeWithDevTools(applyMiddleware(
thunkMiddleware,
createLogger({ collapsed: true })
))
)
}
任何帮助将不胜感激!
更新:
还想从redux添加我的记录器输出:
奇怪的是,该动作没有被解雇吗?有效载荷似乎仍然是错误的?
答案 0 :(得分:1)
Redux Persist有时在服务器端渲染中工作异常。减速器的持久性可能存在问题。这些动作和减速器对我来说似乎很好。我和你一样。所以我写了一个样板示例。所以
https://github.com/fazlulkarimweb/with-next-redux-wrapper-redux-persist
到目前为止,还没有Next社区的官方示例。我认为试图找到解决方案的人会从此样板中获得帮助。