如何在Reactor中删除数组中的对象?

时间:2019-12-04 08:50:09

标签: reactjs react-redux reducers

我知道我的问题已经问了,但我不这样认为:

我想在减速机上删除一个项目,但我尝试的所有方法均无效。

我尝试了很多事情,但是在此之后2天,我想我需要帮助!

这是调度员:

store.dispatch({
     type: 'REMOVE_COIN',
     payload: {
          id:coinId
      }
 })

这是减速器:

const intialState = {
}

const coinReducer = (state = intialState, action) => {
    switch(action.type){
        case "REGISTER_COIN":
            return {
                ...state,
                [action.payload.id]: {
                    id:action.payload.id,
                    position:action.payload.position,
                }
            }
        case "REMOVE_COIN":

            const newState = Object.assign([], state)
            // console.log(newState)

            // if (newState.includes(Object(action.payload.id)) > -1) {
                // console.log('OUI')
            // }else{
                // console.log('NON')
            // }

            // const newState = [...state]
            // const index = newState.findIndex(coin => coin.id == action.payload.id)
            // if (index !== -1) {
            //     newState.splice(index, 1);
            //     console.log(newState)
            // }

            const finalState = newState.filter(coin => coin.id !== action.payload.id)
            console.log(finalState)
            // const coinId = action.payload.id

            // // console.log(newState)

            // const indexOfCatToDelete = newState.findIndex(coin => coin.id == String(action.payload.id))


            // console.log(indexOfCatToDelete)
            // newState.splice(indexOfCatToDelete, 1)
            // console.log(newState)
            // return newState     
            // return {
            //     state : newState.filter( (item, index) => index !== action.index)
            //  }    
            // return finalState
            // const numIndex = parseInt(action.index)
            // return {
            //     state: [
            //     ...state.slice(0, numIndex),
            //     ...state.slice(numIndex+ 1)
            //     ]
            // }
        default:
            return state
    }
}

export default coinReducer

我让所有评论都显示了我尝试过的所有内容。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您需要将您的初始状态作为数组来起作用。或向其中添加coins属性,该属性是一个数组:

const initialState = [];
// Or 
const initialState = {coins: []}

确保您确实收到了action的{​​{1}},然后可以在化简器中返回过滤后的状态:

payload.id

编辑:回头看一下减速器,我注意到您将状态作为对象,其中硬币ID是一个道具。在这种情况下,您需要通过对象键来过滤状态:

case "REMOVE_COIN":
  // OR state.coins.filter if that's what you have on the state
  return state.filter(coin => String(coin.id) !== String(action.payload.id));