数组中的 react-redux 更新项不会重新呈现
react-redux update item in array doesn't re-render
我有一个 reducer,它 returns 一个对象中有一个数组的对象。我呈现数组中的项目列表,当用户单击该项目时,我想重新呈现数组(或至少是项目)。我创建了一个显示问题的 jsbin:
https://jsbin.com/fadudeyaru/1/edit?js,console,output
要重现该问题,请单击 + 或 - 按钮几次以创建历史记录。然后单击其中一个历史记录项。您会注意到控制台日志注意到了事件并更新了状态,但列表并未重新呈现。这可以通过在单击列表中的项目 后再次单击 +/- 按钮来验证。之后你会看到它正确呈现。
问题是为什么 react-redux 不会导致重新渲染?我需要做些什么来解决这个问题吗?
提前致谢。
redux 中的状态是不可变的。这意味着 reducer 应该为每个突变创建一个新状态。最好在存在阵列时进行深度克隆。以下代码对您的代码进行近似深度克隆以使其正常工作。尝试像 lodash/deepClone 这样的实用程序以获得更简单的解决方案。
const counter = (state = {count:0, history:[]}, action) => {
let {count} = state;
let history = [...state.history];
switch (action.type) {
case 'SELECT':
history[action.i].selected = true;
break;
case 'INCREMENT':
history.push({count,selected:false});
count++;
break;
case 'DECREMENT':
history.push({count,selected:false});
count--;
break;
default:
break;
}
console.log("count reducer: ", {count,history})
return {count,history};
}
我有一个 reducer,它 returns 一个对象中有一个数组的对象。我呈现数组中的项目列表,当用户单击该项目时,我想重新呈现数组(或至少是项目)。我创建了一个显示问题的 jsbin:
https://jsbin.com/fadudeyaru/1/edit?js,console,output
要重现该问题,请单击 + 或 - 按钮几次以创建历史记录。然后单击其中一个历史记录项。您会注意到控制台日志注意到了事件并更新了状态,但列表并未重新呈现。这可以通过在单击列表中的项目 后再次单击 +/- 按钮来验证。之后你会看到它正确呈现。
问题是为什么 react-redux 不会导致重新渲染?我需要做些什么来解决这个问题吗?
提前致谢。
redux 中的状态是不可变的。这意味着 reducer 应该为每个突变创建一个新状态。最好在存在阵列时进行深度克隆。以下代码对您的代码进行近似深度克隆以使其正常工作。尝试像 lodash/deepClone 这样的实用程序以获得更简单的解决方案。
const counter = (state = {count:0, history:[]}, action) => {
let {count} = state;
let history = [...state.history];
switch (action.type) {
case 'SELECT':
history[action.i].selected = true;
break;
case 'INCREMENT':
history.push({count,selected:false});
count++;
break;
case 'DECREMENT':
history.push({count,selected:false});
count--;
break;
default:
break;
}
console.log("count reducer: ", {count,history})
return {count,history};
}