【问题标题】:State not updating in SunEditor onChange eventSunEditor onChange 事件中的状态未更新
【发布时间】:2022-01-25 01:42:13
【问题描述】:

版本

  • 下一个:12.0.7
  • suneditor:2.41.3
  • suneditor-react: 3.3.1
const SunEditor = dynamic(() => import("suneditor-react"), {
  ssr: false,
});
import "suneditor/dist/css/suneditor.min.css"; // Import Sun Editor's CSS File
// states
const [toggle, setToggle] = useState<boolean>(false);
const [content, setContent] = useState<string>("");
useState(() => {
  console.log(toggle, content);
}, [toggle, content]);
// render
return (
  <SunEditor
    onChange={(content) => {
      setToggle(!toggle);
      setContent(!content);
    }
  />
);

当我键入控制台面板时,总是显示只有 content 已更改,但 toggle 未更改。

我真的不知道会发生什么,我只想在SunEditoronChange事件中设置其他状态,但我不能。谁能告诉我如何解决这个问题?

【问题讨论】:

  • setToggle 调用更改为setToggle((value) =&gt; !value); 能否解决问题?
  • @juliomalves 哦,那工作!太感谢了。但是......它似乎重新渲染/更新两次,因为控制台面板每次切换记录两次,但这没关系。你能解释一下为什么会发生这种情况,为什么它应该在回调中设置带有返回值的状态。
  • console.log(toggle, content) 可能会发生两次,因为togglecontent 状态变量都在onChange 内更改。

标签: reactjs typescript next.js suneditor


【解决方案1】:

您可以使用setToggle 函数内的函数来获取当前状态值并返回该状态变量的修改值。

<SunEditor
    onChange={(content) => {
        setToggle((value) => !value);
        setContent(content);
    }
/>

由于setState 的异步特性,将函数而不是值传递给状态设置器将为您提供获取组件状态的可靠方法。在根据之前的状态设置状态时,这是推荐的方法。

【讨论】:

    猜你喜欢
    • 2023-01-03
    • 1970-01-01
    • 2019-09-21
    • 2021-11-29
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多