![](/img/trans.png)
[英]What is the best practice to fetch non-api data in Next.js(deploying through Vercel)
[英]What are the best practices to initialize a Next.js webapp with data from an API and adding it to the state?
我正在使用 Zusand 進行 state 管理(盡管我想同樣的原則適用於所有 state 管理庫,例如 Redux 或 Recoil)。 我想過並嘗試過:
getStaticProps()
獲取數據並使用useEffect()
將數據推送到 state。 問題是在加載特定頁面之前,數據不會推送到 state。 我不想使用getInitialProps()
,因為它已被棄用。useEffect()
將數據推送到 state 。 這樣,我可以使用 state 中的數據自由填充頁面,並且只需要一次 API 調用。 下面的例子:function MyApp({ Component, pageProps }) {
// Load data from api with SWR
const fetcher = (url) => fetch(url).then((res) => res.json());
const { data, error } = useSWR(
"https://example.com/api",
fetcher
);
// Get data setter from state
const setData = useStore((state) => state.setData);
// When data is fetched successfully, populate state with data
useEffect(() => {
if (data) {
setData(data);
}
}, [data]);
if (error) return "Error has occured";
if (!data) return "Loading...";
return (
<Layout>
<Component {...pageProps} />
</Layout>
);
}
export default MyApp;
有沒有更好的方法來獲取數據並在第一次加載應用程序時使用它來填充 state? 最佳實踐是什么?
我使用 Zusstand 上下文提供程序以正確的方式工作,並使用 Nextjs pageProps
和getStaticProps()
對其進行初始化。
_app.js
function MyApp({ Component, pageProps }) {
const createStore = initStore(pageProps.initZustand);
return (
<Provider createStore={createStore}>
<Component {...pageProps} />
</Provider>
);
}
export default MyApp;
store.js
export const { Provider, useStore } = createContext();
let store = {
names: ["Name 1", "Name 2", "Name 3"],
random: [],
setRandom: (data) => {
set((state) => ({ random: data }));
},
};
export const initStore = (data) => {
const createStore = () =>
create(
devtools((set, get) => ({
...store,
...data,
}))
);
return createStore;
};
index.js 獲取靜態屬性:
export async function getStaticProps(context) {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
const posts = await res.json();
return {
props: {
initZustand: {
posts: posts,
},
},
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.