Reactjs 如何在react中删除reducer中数组中的对象?
我知道我的问题已经被问到了,但我不这么认为: 我想删除减速机上的一个项目,但我尝试的每件事都不起作用 我尝试了很多东西,但是在这两天被阻止后,我想我需要帮助 这是调度员:Reactjs 如何在react中删除reducer中数组中的对象?,reactjs,react-redux,reducers,Reactjs,React Redux,Reducers,我知道我的问题已经被问到了,但我不这么认为: 我想删除减速机上的一个项目,但我尝试的每件事都不起作用 我尝试了很多东西,但是在这两天被阻止后,我想我需要帮助 这是调度员: store.dispatch({ type: 'REMOVE_COIN', payload: { id:coinId } }) 这是减速器: const intialState = { } const coinReducer = (state = intialState
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
我让所有的评论都显示出我所做的一切
谢谢你的帮助 您需要将初始状态设置为一个数组,这样才能工作。或者向其添加
coins
属性,这是一个数组:
const initialState = [];
// Or
const initialState = {coins: []}
确保您正在使用payload.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));
编辑:回顾你的减速机,我注意到你将状态作为一个对象,其中硬币id是一个道具。在这种情况下,需要按对象键过滤状态:
case "REMOVE_COIN":
return Object.keys(state)
.filter(key => key !== String(action.payload.id))
.reduce((obj, key) => {
obj[key] = state[key];
return obj;
}, {});