今天我开始构建一个 Next.js 应用程序。我正在使用 Redux ( next-redux-wrapper
) 来管理我的全局状态。(我还在使用 redux-persist 坚持一些减速器)。我刚刚实施redux-thunk
并立即得到一个非常奇怪的错误。我真的不知道为什么会发生这个错误。我基本上只是做了设置,没有创建任何减速器(创建减速器后错误仍然存在)。这不是第一次,我做了同样的设置没有任何问题,但那一次我无法摆脱那个错误。
错误代码
警告:不建议在严格模式下使用 UNSAFE_componentWillReceiveProps,这可能表明代码中存在错误。有关详细信息,请参阅 https://reactjs.org/link/unsafe-component-lifecycles。***
- 将数据获取代码或副作用移动到 componentDidUpdate。
- 如果您在 props 更改时更新状态,请重构您的代码以使用 memoization ***技术或将其移动到静态 getDerivedStateFromProps。了解更多信息: https ://reactjs.org/link/derived-state 请更新以下组件:withRedux(MyApp)
如果您需要更多代码,请询问。我真的没有更多。也许package.json
。
_app.js
import App from 'next/app'
import { wrapper } from '../reduxStore/store'
import { useStore } from 'react-redux'
import PropTypes from 'prop-types'
function MyApp({ Component, pageProps }) {
const store = useStore((state) => state)
return <Component {...pageProps} />
}
MyApp.propTypes = {
Component: PropTypes.func,
pageProps: PropTypes.object,
}
export default wrapper.withRedux(MyApp)
store.js
import { createStore, applyMiddleware, combineReducers } from 'redux'
import { HYDRATE, createWrapper } from 'next-redux-wrapper'
import thunkMiddleware from 'redux-thunk'
import userReducer from './reducers/userReducer'
const bindMiddleware = (middleware) => {
if (process.env.NODE_ENV !== 'production') {
const { composeWithDevTools } = require('redux-devtools-extension')
return composeWithDevTools(applyMiddleware(...middleware))
}
return applyMiddleware(...middleware)
}
const combinedReducer = combineReducers({
user: userReducer,
})
const reducer = (state, action) => {
if (action.type === HYDRATE) {
const nextState = {
...state, // use previous state
...action.payload, // apply delta from hydration
}
// if (state.count.count) nextState.count.count = state.count.count // preserve count value on client side navigation
return nextState
} else {
return combinedReducer(state, action)
}
}
export const makeStore = ({ isServer }) => {
if (isServer) {
//If it's on server side, create a store
return createStore(reducer, bindMiddleware([thunkMiddleware]))
} else {
//If it's on client side, create a store which will persist
const { persistStore, persistReducer } = require('redux-persist')
const storage = require('redux-persist/lib/storage').default
const persistConfig = {
key: 'nextjs',
whitelist: ['user'], // only counter will be persisted, add other reducers if needed
storage, // if needed, use a safer storage
}
const persistedReducer = persistReducer(persistConfig, reducer) // Create a new reducer with our existing reducer
const store = createStore(
persistedReducer,
bindMiddleware([thunkMiddleware]),
) // Creating the store again
store.__persistor = persistStore(store) // This creates a persistor object & push that persisted object to .__persistor, so that we can avail the persistability feature
return store
}
}
export const wrapper = createWrapper(makeStore)