首页 > 解决方案 > 将 React useMemo() 与 TypeScript 一起使用时,不能分配给类型 '() => void' 错误?

问题描述

我有一个非常简单的带有打字稿的反应应用程序。

import React, { useState, useMemo } from "react";
import { Editor as Draft, EditorState } from "draft-js";

const Editor: React.FC = () => {
  const [editorState, setEditorState] = useState<() => EditorState>(() =>
    EditorState.createEmpty()
  );

  const handleEditorChange = useMemo(
    (nextEditorState: EditorState) => setEditorState(nextEditorState),
    [editorState]
  );

  return (
    <div>
      <Draft editorState={editorState} onChange={handleEditorChange} />
    </div>
  );
};

export default Editor;

我正在尝试使用它,useMemo()但是当我换行时handleEditorChangeuseMemo我收到以下错误:

argument of type '(nextEditorState: EditorState) => void' is not assignable to parameter of type '() => void'  

如何在这里正确使用 TypeScript 并摆脱错误?

标签: reactjstypescriptdraftjs

解决方案


useMemo用于记忆提供给它的函数的返回值,但您将它用作 onChange 处理程序。

所以删除它并只使用该函数作为处理程序

const handleEditorChange = (nextEditorState: EditorState) => 
  setEditorState(nextEditorState)

其次,您将状态键入为返回EditorState不正确的函数,您希望类型为EditorState.

TypeScript 还可以推断类型,因此您甚至不需要键入它

const [editorState, setEditorState] = useState(EditorState.createEmpty())

推荐阅读