当状态是对象的对象时组件重新渲染

Component re-render when state is an object of objects

我在一个页面上有多个 redux 表单。渲染组件时,我能够使用 form 属性创建不同的表单。

<ItemDetail form={itemName} />

但我正在使用 redux 存储来维护我的组件的状态。我正在以某种方式动态创建 redux 存储:

const currentState = { ...state };
currentState[action.itemName].itemHash = 'fetching';
currentState[action.itemName].itemType = '';
return currentState;

问题是当我更新此对象的任何 属性 时,组件不会重新呈现。

如果我这样做:

const currentState = { ...state };
currentState[action.itemName]={};
currentState[action.itemName].itemHash = 'fetched';

它正确地重新渲染了组件。但如果我只是这样做:

const currentState = { ...state };
currentState[action.itemName].itemHash = 'fetching';

它不会重新渲染它。

虽然有一种解决方法可以深度克隆项目对象或与上面显示的相同方法。但不确定这是否是一个好方法,或者我们是否可以用更干净的方式来做。

感谢任何帮助!

您的组件没有重新渲染,因为 React 将对状态进行浅层比较。它通过迭代正在比较的状态的键并在每个对象中的键值不严格相等时返回 true 来实现。

在您的情况下,您需要为 currentState[action.itemName] 属性创建一个新对象:

    const currentState = { ...state };

    currentState[action.itemName] = {
      ...currentState[action.itemName],
      itemHash = 'fetching',
      itemType = '';
    };

    return currentState;