簡體   English   中英

react-bootstrap-typeahead 錯誤:從生命周期方法內部調用了 flushSync

[英]react-bootstrap-typeahead error: flushSync was called from inside a lifecycle method

我正在嘗試在項目中使用 react-bootstrap-typeahead。 當我在在線沙箱中試用時,它按預期工作(我可以展開下拉菜單並進行選擇)。 當我嘗試在我的項目中使用它時,該組件被渲染,但單擊它會使頁面崩潰並出現錯誤:

react-dom.development.js:24447 Uncaught Error: flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.

下面是我試圖渲染的測試組件,我從另一個堆棧溢出帖子中獲取

import React, { useState } from 'react';
import { Typeahead } from 'react-bootstrap-typeahead';

const MyTypeahead= () => {
const [selected, setSelected] = useState([]);
return (
<div>
  <Typeahead
    id="basic-typeahead-example"
    labelKey="state"
    onChange={setSelected}
    options={[
      { state: 'AL' },
      { state: 'AK' },
      { state: 'AZ' },
      { state: 'AR' },
      { state: 'CA' },
    ]}
    placeholder="Choose a state..."
    selected={selected}
  />
</div>
);
};
export default MyTypeahead;

少了什么東西? 我覺得我對狀態管理的理解存在某種巨大的差距。

不要在 onChange 中直接傳遞 useState-update 函數。 而是編寫一個回調並將其傳入。此外,在您的情況下,您不需要在選項中使用對象,只需使用純字符串:

const MyTypeahead = () => {
  const [selected, setSelected] = useState([]);
  const handleChange = (selected) => setSelected(selected);
  return (
    <div>
      <Typeahead
        id="basic-typeahead-example"
        labelKey="state"
        onChange={handleChange}
        options={["AL", "AK", "AZ", "AR", "CA"]}
        placeholder="Choose a state..."
        selected={selected}
      />
    </div>
  );
};
export default MyTypeahead;

https://codesandbox.io/s/adoring-pare-33v6oh

關於 flushSync - 這是存儲庫中的一個已知問題:

https://github.com/ericgio/react-bootstrap-typeahead/issues/715

即使顯示了錯誤消息,typeahead 組件似乎也可以正常工作。 我建議在修復之前忽略此錯誤消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM