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

查看:56
本文介绍了数组中的 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,控制台,输出

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

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天全站免登陆