【发布时间】:2020-03-27 22:40:08
【问题描述】:
我正在使用 Redux 在这个项目/示例中实现一个基本的 Like 计数器
https://codesandbox.io/s/github/mralwin/Reduxstagram
这是用于管理喜欢状态增加的以下代码:
动作
export function increment(index) {
return {
type: "INCREMENT_LIKES",
index
};
}
减速器
function posts(state = [], action) {
switch (action.type) {
case "INCREMENT_LIKES":
const i = action.index;
return [
...state.slice(0, i), // before the one we are updating
{ ...state[i], likes: state[i].likes + 1 },
...state.slice(i + 1) // after the one we are updating
];
default:
return state;
}
}
组件
<button onClick={this.props.increment.bind(null, i)} className="likes">
现在我想添加一个减少函数作为练习来管理减少状态喜欢,以及问题出在哪里。
查看代码:
动作
export function decrease(index) {
return {
type: 'DECREASE_LIKES',
index: i
};
}
Reducer => 添加了 DECREASE_LIKES 案例
function rooms(state = [], action) {
switch (action.type) {
case 'INCREMENT_LIKES' :
const i = action.index;
return [
...state.slice(0, i),
{...state[i], likes: state[i].likes + 1 },
...state.slice(i + 1)
];
case 'DECREASE_LIKES' :
return [
...state.slice(0, i),
{...state[i], likes: state[i].likes - 1 },
...state.slice(i + 1)
];
default:
return state;
}
}
组件
<button onClick={this.props.decrease.bind(null, i)} className="likes">
虽然我在调试,但在 DECREASE 的情况下,state 似乎是未定义的。
我做错了什么?我该如何解决?
【问题讨论】:
标签: javascript reactjs redux state bind