React Hooks--使用lodash的deepCopy不会导致重渲染。

问题描述 投票:0回答:1

我使用React.js与钩子,试图改变一个嵌套的状态值。由于我不想直接突变状态,所以我使用lodash的 "CloneDeep "函数。状态改变成功了,但是重新渲染并没有发生,所以我在页面中看不到变化,直到我重新输入它。更多信息(在我的web控制台中检查结果)。console.log(logicalLinesDeepCopy == logicalLines); => false console.log(logicalLinesDeepCopy === logicalLines); => false console.log(logicalLines[menuLineId].content[menuSentenceId].triggers); => [] console.log(logicalLinesDeepCopy[menuLineId].content[menuSentenceId].triggers); => [(对象)]

我的代码。

// relevant imports:
import CloneDeep from "lodash/cloneDeep";

// relevant state initiation: (the value is filled before I call the relevant function)
const [logicalLines, setLogicalLines] = useState(null);

// relevant function:
const addTriggerToListInState = (trigger) => {
    // Deep copy:
    let logicalLinesDeepCopy = CloneDeep(logicalLines);
    // Change the deep copy:
    const lineCopy = logicalLinesDeepCopy[menuLineId];
    const triggersListCopy = lineCopy.content[menuSentenceId].triggers;
    triggersListCopy.push(trigger);
    // Some debug checks:
    console.log(logicalLinesDeepCopy == logicalLines);
    console.log(logicalLinesDeepCopy === logicalLines);
    console.log(logicalLines[menuLineId].content[menuSentenceId].triggers);
    console.log(logicalLinesDeepCopy[menuLineId].content[menuSentenceId].triggers);
    // Setting the state:
    setLogicalLines(logicalLinesDeepCopy);
  };

看起来新状态的引用和嵌套内容都和之前的不一样,那为什么不引起重新渲染呢,怎么改才能引起重新渲染呢?

Sapir

javascript reactjs react-hooks lodash
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.