数组中的react-redux更新项不会重新呈现 [英] react-redux update item in array doesn't re-render

查看:207
本文介绍了数组中的react-redux更新项不会重新呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个reducer,它返回一个带有对象数组的对象。我渲染数组中的项目列表,当用户点击该项目时,我想重新渲染数组(或至少是项目)。我创建了一个显示问题的jsbin:

I have a reducer which returns an object with an array in the object. I render the list of items in the array and when the user clicks on that item I want to re-render the array (or at least the item). I've created a jsbin that shows the problem:

https://jsbin.com/fadudeyaru/1/edit?js,console,output

要重现此问题,单击+或 - 按钮几次以创建历史记录。然后单击其中一个历史记录项。您会注意到控制台日志会通知事件,并更新状态,但不会重新呈现列表。 点击列表中的项目后,再次单击+/-按钮可以验证这一点。之后你会看到它正确渲染。

To reproduce the issue, click the + or - button a few times to create a history. then click on one of the history items. you'll notice that the console log notices the event, and updates the state, but the list is not re-rendered. This can be verified by clicking the +/- button again after clicking on an item in the list. after that you'll see that it renders correctly.

问题是为什么react-redux不会导致它被重新渲染?我需要做些什么来强制解决这个问题?

Question is why does react-redux not cause this to be re-rendered? is there something I need to do to force the issue?

提前致谢。

推荐答案

redux中的状态是不可变的。这意味着reducer应该为每个突变创建一个新状态。优选地,当存在阵列时应该进行深度克隆。以下代码为您的代码执行近似深层克隆。尝试像lodash / deepClone这样的实用程序,以获得更简单的解决方案。

State in redux is immutable. This means that reducer should create a new state for every mutation. Preferably, a deep clone should be done when arrays are present. The following code does an approximate deep clone for your code to work. Try utilities like lodash/deepClone for an easier solution.

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

这篇关于数组中的react-redux更新项不会重新呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆