Redux reducer,检查状态数组和更新状态中是否存在值

Jam*_*111 4 arrays reducers reactjs redux

所以我有一个数组chosenIds[],基本上会有一个列表ids (numbers).但我在我的reducer中访问状态时遇到问题,无法检查是否ID I parsed to my action在数组中.

  const initialState = {
  'shouldReload': false,
  'chosenIds': [],
};

export default function filter(state = initialState, action) {
  switch (action.type) {


 case ADD_TYPE:
      console.log(state.chosenIds, "Returns undefined???!!!");

      // Check if NUMBER parsed is in state
      let i = state.chosenIds.indexOf(action.chosenId);

      //If in state then remove it
      if(i) {
        state.chosenIds.splice(i, 1);
        return {
          ...state.chosenIds,
          ...state.chosenIds
        }
      }
      // If number not in state then add it 
      else {
        state.chosenIds.push(action.chosenId)
        return { ...state.chosenIds, ...state.chosenIds }
      }
Run Code Online (Sandbox Code Playgroud)

我不确定发生了什么......但是当我记录时state.chosenIds,它返回undefined?它甚至不返回初始的空数组[].

基本上这个函数假设是检查action.chosenId是否在state.chosenIds,如果是,则删除该action.chosenId值,如果不是,则将其添加action.chosenId到状态.

mar*_*son 11

我在这里看到一些不同的问题.

首先,你正在使用splice()push()一个已经在该州的阵列上.这是直接突变,打破了Redux.您需要复制数组,然后修改该副本.

其次,对象传播使用看起来不正确.您正在使用它,好像"selectedIds"是一个对象,但它是一个数组.此外,您正在复制点差.这导致返回的状态不再具有名为"selectedIds"的字段.

第三,Array.indexOf()如果找不到则返回-1,实际上它被称为"truthy",因为它不是0.因此,当前的if/else将不会按预期执行.

我会把你的reducer改写成这样:

export default function reducer(state = initialState, action) {
    switch(action.type) {
        case ADD_TYPE:
            let idAlreadyExists = state.chosenIds.indexOf(action.chosenId) > -1;
            // make a copy of the existing array
            let chosenIds = state.chosenIds.slice();

            if(idAlreadyExists) {
                chosenIds = chosenIds.filter(id => id != action.chosenId);                
            }     
            else {
                // modify the COPY, not the original
                chosenIds.push(action.chosenId);            
            }      

            return {
                // "spread" the original state object
                ...state,
                // but replace the "chosenIds" field
                chosenIds
            };
        default:
            return state;
    }    
}
Run Code Online (Sandbox Code Playgroud)

  • 因为对象和数组是JavaScript中的传递引用.当您改变状态时,您将更改先前的状态并使先前的状态与新状态相同.因此react-redux不再能检测到旧的和新的之间的变化,因此它不会更新. (4认同)