繁体   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