我试图通过触发页面中getInitialProps中的"getItems"操作来从API获取数据。(假设是A页(
如果我通过链接(下一个/链接(从其他页面转到页面A,则可以成功获取数据。
但是,如果我在页面A中刷新,数据永远不会被提取,我必须通过触发getItems操作手动提取数据。
有人能告诉我,即使在刷新页面时,我也应该如何获取数据吗?
_app.js
const MyApp = props => {
const { Component, pageProps, store } = props
return (
<>
<Head>
<link rel='stylesheet' href='/styles/global.css' />
</Head>
<Provider store={store}>
<MainLayout>
<Component {...pageProps} />
</MainLayout>
</Provider>
</>
)
}
MyApp.getInitialProps = async ({ Component, ctx }) => {
const pageProps = Component.getInitialProps
? await Component.getInitialProps(ctx)
: {}
return { pageProps }
}
export default withRedux(store)(MyApp)
pageA.js
import Head from 'next/head'
import Link from 'next/link'
import { connect } from 'react-redux'
import { getItems, addItem } from '../../store/actions/itemAction'
import { GET_ITEMS } from '../../store/types'
const Index = props => {
return (
<>
<Head>
<title>Item List</title>
<link rel='stylesheet' href='/styles/css_pages/shop.css' />
</Head>
<div><div>
</>
)
}
Index.getInitialProps = async ({ store }) => {
await store.dispatch(getItems())
return {}
}
const mapStateToProps = state => ({
goods: state.item.goods,
})
const mapDispatchToProps = dispatch => ({
getItems: () => dispatch(getItems()),
addItem: () => dispatch(addItem()),
})
export default connect(mapStateToProps, mapDispatchToProps)(Index)
itemAction.js
import fetch from 'isomorphic-unfetch'
import { GET_ITEMS } from '../types'
export const getItems = () => {
return dispatch => {
fetch('http://localhost:5000/item')
.then(res => res.json())
.then(data => dispatch({ type: GET_ITEMS, payload: data }))
.catch(err => console.error(err))
}
}
itemReducer.js
import { GET_ITEMS } from '../types'
const initialState = { goods: [], loading: false }
const itemReducer = (state = initialState, action) => {
switch (action.type) {
case GET_ITEMS:
return {
...state,
goods: action.payload,
loading: false,
}
default:
return state
}
}
export default itemReducer
store.js
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from './rootReducer'
const bindMiddleware = middleware => {
if (process.env.NODE_ENV !== 'production') {
const { composeWithDevTools } = require('redux-devtools-extension')
return composeWithDevTools(applyMiddleware(...middleware))
}
return applyMiddleware(...middleware)
}
export const store = () => createStore(rootReducer, bindMiddleware([thunk]))
rootReducer.js
import { combineReducers } from 'redux'
import itemReducer from './reducers/itemReducer'
const rootReducer = combineReducers({
item: itemReducer
})
export default rootReducer
在返回和呈现之前,您应该等待页面A的getInitialProps
中的getItems
操作响应。
我认为如果你尝试使用await
,它会解决你的问题:
Index.getInitialProps = async ({ store }) => {
await store.dispatch(getItems())
return {}
}
我会尝试研究这个例子https://github.com/vercel/next.js/blob/canary/examples/with-redux-wrapper/store/store.js
建议使用next-redux-wrapper
软件包包装页面。然后您将在Index.getInitialProps
上获得store
对象