[英]React: Decrease action causes undefined state in Redux reducer
我正在使用 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情况下,状态似乎是未定义的。
我究竟做错了什么? 我该如何解决?
看起来变量i
未在减速器 switch 语句的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; } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.