我正在尝试使用React和Redux创建一个计数器示例,但我无法更新其中单击它的当前项的状态。
点击事件,我在当前项目的有效负载中传递了id。
return this.props.peliculas.map(movie => {
return <li onClick={() => this.handleClicks(movie.id)} key=
{movie.id}>{movie.title}</li>
});
我在类中有函数来处理事件:
handleClicks(peli){
this.props.onLiClick(peli);
}
派遣部分:
const mapStateToProps = state => {
return {
peliculas: state.movies.peliculas
}
};
const mapDispatchToProps = dispatch => {
return {
onLiClick: (id) => dispatch({ type: 'ADD_CLICK', payload: {id} })
}
};
减速机
const laspelis = {
peliculas: [{title: 'T1', id: 1, clicks: 0}, {title: 'T2', id: 2, clicks: 0}],
isActive: false
};
export const movies = (state= laspelis, action) => {
switch (action.type) {
case 'ADD_CLICK':
//How to update the current item inside of the reducer?
// After click the current item add 1 to the clicks property
// If the item has id: 2 => {title: 'T2', id: 2, clicks: 1}
return {
...state,
peliculas: [{title: 'Otro 1', id:1},{title: 'Otro 2', id:2}]
}
default:
break;
}
return state;
};
我将click事件正确链接并将操作发送到reducer,(我只是部分显示代码)
感谢。
答案 0 :(得分:1)
您需要找到要按ID更新的项目,将其替换为新项目,而不要忘记更改整个数组
return {
...state,
peliculas: state.peliculas.map(item => {
if(item.id === payload.id) {
return { ...item, clicks: item.clicks + 1}
}
return item;
})
}