在 next.js 中,我们可以在 getServerSideProps 中请求 api 并通过 props 将数据传递给页面,如下所示:
方法1:(下一个默认方法)
const Page: NextPage = ({page}) => {
return <div>{JSON.stringify(data)}</div>;
};
// This gets called on every request
export async function getServerSideProps() {
// Fetch data from external API
const res = await fetch(`https://.../data`)
const data = await res.json()
// Pass data to the page via props
return { props: { data } }
}
export default Page
我在大型项目中工作所以我想只使用 thunk 管理所有服务器和客户端请求,然后将其存储到 redux 并在页面中使用,如下所示:
方法 2:(使用 next-redux-wrapper)
import React from 'react';
import {NextPage} from 'next';
import {useSelector} from 'react-redux';
import {wrapper, State, fetchData } from '../store';
const Page: NextPage = () => {
const {data} = useSelector(state => state);
return <div>{JSON.stringify(data)}</div>;
};
export const getServerSideProps = wrapper.getServerSideProps(store => ({req, res, ...etc}) => {
store.dispatch(fetchData());
});
export default Page;
我想知道哪种方法更好?使用第二种方法将所有预渲染数据和应用程序的客户端状态存储在 redux 中是否是反模式?