当用户单击edit时,我试图更新建筑物的名称和图像。我正确调度了动作,我认为尝试复制先前的state
并用新值更新它的逻辑是错误的,因为我没有看到该值被更新。只是恢复了以前的状态。请帮帮我吧!
这是我的代码:
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
答案 0 :(得分:0)
与商店连接的组件基本上只与Redux状态对话。 例子
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
将状态分配给所需的更改,然后返回该状态
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