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

时间:2019-01-29 07:34:41

标签: reactjs redux redux-form

我在一页上有多个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';

它不会重新渲染它。

尽管有一种解决方法,可以深度克隆项对象,或采用与上述相同的方法。但是不确定这是否是一个好方法,或者我们是否可以采用一种更简洁的方法。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

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

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

    const currentState = { ...state };

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

    return currentState;
相关问题