我正在使用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
};
}
减速器 =>添加了 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">
虽然我正在调试,但在减小情况下,状态是不确定的。
我在做什么错?我该如何解决?
答案 0 :(得分:1)
在reducers switch语句的i
情况下,似乎未定义变量DECREASE_LIKES
。因此,这将导致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' : {
// Use a different variable for visual distinction/clarity
const j = action.index;
// Use j from action index in reduction logic for this action
return [
...state.slice(0, j),
{...state[j], likes: state[j].likes - 1 },
...state.slice(j + 1)
];
}
default:
return state;
}
}