基于此info从官方 NextJS 文档中,他们推荐使用 getServerSidedProps 和 getStaticProps 而不是 getInitialProps。
我想在服务器上将一些数据预加载到 Redux 状态。
注意 :我使用@redux/toolkit 包
所以我有基本的商店设置:
import reducer from './reducer' // this is just a combineReducers ...
export const store = configureStore({ reducer });
我的自定义 _app.js
import { store } from '../store'
<Provider store={store}>
<Component {...pageProps} />
</Provider>
现在这是我面临的问题
在 index.js 文件中我有这样的东西
import { store } from '../store'
...
export const getServerSideProps = async (ctx) => {
const data = await fetchSomeData();
// here I add some data to the store
store.dispatch(someAction(data));
return { props: {} }
}
数据是在服务器端设置在存储中的,但是当我在客户端时,存储是空的。有谁知道如何在服务器上预加载数据?我不想使用 componentDidMount 的 useEffect 并在客户端上设置该数据。我知道有一个库正在解决这个问题,但它正在使用 getInitialProps ,我想看看是否可以通过这种方式完成某些事情。
最佳答案
getServerSidedProps
如果您仅在服务器端渲染时需要数据,则应使用该数据。但是,如果当用户从该页面开始(您在服务器上获取数据)以及客户端导航到该页面时,您需要在这两种情况下的数据,最好使用 getInitialProps
获取数据(通过 redux-toolkit
的 createAsyncThunk
)。
无论如何,getServerSidedProps
和 getInitialProps
您需要将服务器端存储传递给客户端作为初始客户端存储。您可能要考虑使用 next-redux-wrapper对于这个任务。你可以找到一个不错的example here .
此外,您缺少 react-redux
的用法的connect
至mapStateToProps
和 mapDispatchToProps
.
我正在使用 next.js
和 react-redux
与您的配置相似,我正在努力处理获取存储数据和调度操作所需的所有样板代码。所以我创建了connect-initial-props使用户更容易getInitialProps
调度 Action 并使用来自 redux 存储的状态数据。欢迎您以 connect-initial-props 上的示例为例GitHub。
关于reactjs - NextJS,在 getServerSideProps 中预加载 Redux 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61281070/