gpt4 book ai didi

javascript - 来自对象数组的 React redux 计数器示例

转载 作者:行者123 更新时间:2023-12-03 03:07:29 24 4
gpt4 key购买 nike

我正在尝试使用 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} })
}
};

reducer

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;
};

我已正确链接点击事件,并且操作已发送到 reducer ,(我将仅显示部分代码)

谢谢。

最佳答案

您需要通过 id 找到要更新的项目,将其替换为新的,并且不要忘记更改整个数组

   return {
...state,
peliculas: state.peliculas.map(item => {
if(item.id === payload.id) {
return { ...item, clicks: item.clicks + 1}
}

return item;
})
}

关于javascript - 来自对象数组的 React redux 计数器示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47103772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com