问题
For a learning and test project, I'm trying to return immutable redux data from reducer because safe data for component. this is my reducer code :
function itemsReducer(state = [], action) {
switch(action.type) {
case 'ITEMS':
return [...action.data]
default:
return state
}
}
And this is my loop code :
<ul>
{
this.props.items.map((item) => (
<li>{item.name.first} {item.name.last}</li>
))
}
</ul>
now every things work right, but after change on props with this method :
change() {
this.props.items[0] = 'empty'
}
and after loading again items I have this error :
TypeError: Cannot read property 'first' of undefined
Apparently the items did not copy with spread syntax in my reducer and all changes override on that. after executing the data load action at all the index #0 is 'empty'
Thank you
回答1:
You shouldn't be mutating the props directly in component, instead dispatch an action that updates the result in reducer
change() {
this.props.updateItem({first: 'empty'}, 0);
}
and action creator would be
const updateItem = (item, index) => {
return {type: 'UPDATE_ITEM', item, index}
}
and reducer
function itemsReducer(state = [], action) {
switch(action.type) {
case 'ITEMS':
return [...action.data]
case 'UPDATE_ITEM':
return [...state.slice(0, action.index), {...state[index], ...action.item}, ...state.slice(index+1)];
default:
return state
}
}
来源:https://stackoverflow.com/questions/55511749/how-can-i-return-immutable-data-from-redux-reducer