[Next] 使用redux-saga遭遇之問題

張庭瑋
Nov 14, 2020

--

在上一篇文章提過

Next.js的官網的 redux-saga的範例,如果稍微調整就會有無限轉圈圈的問題

具體來說他的 reducerreducer.js)有兩個問題

  1. 初始狀態沒作為預設值傳入reducer
  2. 初始狀態中的 placeholderData屬性初始宣告為 null,實際的資料型態卻是陣列

所以具體的調整是

// reducer.js
// 4~10行
const initialState = {
count: 0,
error: false,
lastUpdate: 0,
light: false,
placeholderData: [], // placeholderData: null
}
// 12行
function reducer(state = initialState, action) {
// function reducer(state, action) {

然後就開始轉圈了,所以具體的問題到底是在哪裡呢?

具體的問題在 /pages/index.js的21行

// /pages/index.js// 21~24行
if (!store.getState().placeholderData) {
store.dispatch(loadData())
store.dispatch(END)
}

這裡的意思是 placeholderData的值在 if判斷下為 false的情況才去取得資料

也就是原本的 null是能通過的

而改成 []就通不過了

所以改成這樣就可以了

// /pages/index.js// 21行
if (store.getState().placeholderData.length === 0) {

實際上也不是 bug,也不是什麼很難找的錯誤

只是因為這個不會跳錯誤訊息,讓我鬼打牆了好一陣子……

參考:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response