简体   繁体   English

Redux 更新状态数组中的项

[英]Redux updating item in state array

I am trying to update the building's name and image when the user clicks edit .当用户单击 edit 时,我试图更新建筑物的名称和图像。 I am dispatching the action correctly I think my logic with trying to copy the previous state and updating it with the new value is wrong because I am not seeing the value getting updated.我正在正确分派动作我认为我尝试复制以前的state并用新值更新它的逻辑是错误的,因为我没有看到值得到更新。 It is just returning the previous state .Please can some help me out!它只是返回以前的状态。请帮帮我!

This is my code:这是我的代码:

import MyBuilding from '../../models/MyBuilding'
import { CREATE_BUILDING, DELETE_BUILDING , UPDATE_BUILDING} from '../actions/building'

const initialState = {
    building: [],
}
const BuildingReducer = (state=initialState, action) =>{
    switch(action.type){
        case CREATE_BUILDING:
            const newBuilding = new MyBuilding(
                action.buildingData.id,
                action.buildingData.name,
                action.buildingData.image, 
            )
            return { ...state, building: state.building.concat(newBuilding)}

        case DELETE_BUILDING:
            const filteredItems = state.building.filter(cb => cb.id !== action.deleteCB)
            return {...state, building: filteredItems }

        case UPDATE_BUILDING:
            const updatedItems = state.building.map(cb => cb.id === action.updateItem.id ? 
                {...cb, 
                    name: action.updateItem.name,
                    image: action.updateItem.image} : cb
                )
            return {...state, 
                building: updatedItems }
        default: 
            return state
    }
}
export default BuildingReducer

Components connected with the store basically talks with the Redux state only.与 store 连接的组件基本上只与 Redux 状态对话。 example例子

let state = {
building: [1,2,3]
}

console.log({ ...state, building: state.building.concat([4,5,6])}) // you will see all building here 
console.log(state) // but the actual state has not changed 

Assign the state to the changes you want and then return that state将状态分配给您想要的更改,然后返回该状态

case CREATE_BUILDING:
const newBuilding = new MyBuilding(
    action.buildingData.id,
    action.buildingData.name,
    action.buildingData.image,
)
state = { ...state, building: state.building.concat(newBuilding) } // do this
return state

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM