簡體   English   中英

使用 redux 更新 state 時推入反應的工作

[英]Working of push in react while using redux to update the state

以下代碼是我的減速器的代碼,我在容器中調用這些 function

const intialState = {
  counter: 0,
  results: []
};

const reducer = (state = intialState, action) => {
  switch (action.type) {
    case "INCREMENT":
      return {
        ...state,
        counter: state.counter + 1
      };

    case "STORE_RESULT": {
      return {
        ...state,
        results: state.results.push(state.counter)
      };
    }
  }
  return state;
};

export default reducer;

我收到以下錯誤

TypeError: state.results.push is not a function
reducer

1) 我在我的項目中使用 redux 減速機

2) 我正在更新 state,方法是將調度中的類型傳遞到我的容器中

3)我試圖通過推送來更新數組(我知道它返回長度)但我想知道它為什么不工作

4)按照我在 javascript 中嘗試的代碼,一切正常

var a = {
b:[]
}
a.b.push(11)
//output
1

push返回變異array的新length 使用concat代替它返回一個新數組

results : state.results.concat(item)

讓我們假設以下代碼

results : state.results.push('foo')

假設resultslength5 ,上面的代碼將斷言

results : 5

下次您嘗試push results時,這將是您的編譯器的樣子

5.push('foo')

.push 的返回值為

調用該方法的 object 的新長度屬性。

將值添加到stae.results使用concatspread 語法

case "STORE_RESULT": {
  return {
    ...state,
    results: [...state.results, state.counter]
  };
}

您應該在減速器開關中添加默認情況。

並使用[...state.results, state.counter]代替state.results.push(state.counter)

像這樣

const intialState = {
  counter: 0,
  results: []
};

const reducer = (state = intialState, action) => {
  switch (action.type) {
    case "INCREMENT":
      return {
        ...state,
        counter: state.counter + 1
      };

    case "STORE_RESULT": {
      return {
        ...state,
        results: [...state.results, state.counter] // here
      };
    default:
      return state; // here
    }
  }
};

export default reducer;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM