使用 useEffect 的无限循环

时间:2021-01-26 04:01:47

标签: reactjs

为什么下面给了我无限的重新渲染?我有一个带有单个 useEffect 的小组件。第二个参数 [currentData] 是做浅比较还是什么?

useEffect(() => {
    getMyData().then(({ data }) => {
      setData({ ...currentData }, { data });
    });
  }, [currentData]);

1 个答案:

答案 0 :(得分:1)

这是因为当您使用 let YourEditor; ClassicEditor .create(document.querySelector('#edit-reply-modal')) .then(editor => { window.editor = editor; YourEditor = editor; }) $('#toggle-edit-modal').on('click', function() { YourEditor.setData('<p>This is the new Data!</p>'); }) 时,您实际上是在创建一个新对象,一个对新对象的新引用,并且 Javascript 通过引用而不是值来比较对象。因此 button{ margin-top:20px; padding: 5px; color: white; background: #00F; border-radius: 5px; } 的新值将始终与之前不同。这使得流程看起来像这样:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.ckeditor.com/ckeditor5/24.0.0/classic/ckeditor.js"></script> <textarea id="edit-reply-modal"><p>Old Data</p></textarea> <button id="toggle-edit-modal">Fill New Data</button> => ({...currentData}) => currentData => You setData (create new Object) => useEffect detect that currentData changed .这会导致循环。

目前,React it run into the call back, subscribe again 不支持比较深层嵌套对象。但是你可以使用自定义钩子来解决这个问题,我发现了另一个我认为可以帮助的 answer