![](/img/trans.png)
[英]Passing a function as a prop to a Typescript React Functional Component
[英]Passing memoized function down into React Component as a prop causes Typescript error which I can't fix
我有一个组件,它有一些像这样定义的道具。 在这种情况下,prop 是一个函数,它允许我们将数据向上传递到父函数或调用函数
type compProps = {
liftableData: (data: IData[] | undefined | false) => void
}
export const BasicComponent = (props: compProps) => {
const { liftableData } = props
// .... more code here
return <div>Some output</div>
}
然后当我像这样使用 BasicComponent
const [someState, setSomeState] = useState<string>('')
const memodData = useMemo((liftableData: IData[] | undefined | false) => {
setSomeState(liftableData)
}, [])
<BasicComponent liftableData={memodData} />
但是打字稿给了我这个错误,我已经尝试了各种方法来修复它,但没有成功
Type 'void' is not assignable to type '(liftableData: false | IData[] | undefined) => void'.
如何设置 memoized 函数以作为道具传递?如何摆脱错误?
那是因为useMemo
用于变量。 memodData
将是您传递的 useMemo 处理程序的结果:此处(liftableData: IData[] | undefined | false) => { setSomeState(liftableData) }
不返回任何内容 => memodData
无效
您应该改为使用useCallback
来获得一个函数:
const memodData = useCallback((liftableData: IData[] | undefined | false) => {
setSomeState(liftableData)
}, [])
让我们看一下useMemo
类型签名:
function useMemo<T>(factory: () => T, deps: DependencyList | undefined): T
useMemo
的第一个参数应该是一个没有参数的函数,而您试图提供一个带参数的函数。
看这个例子:
let foo = () => { }
let bar = (arg: number) => {
arg.toExponential()
}
foo = bar // error, fn with args is not assignable to fn without args
bar = foo
const withCallback = (fn: () => void) => { }
withCallback(bar) // expected error
为什么你有这个错误? 想象一下,当您尝试将bar
分配给foo
时没有错误。
let foo = () => { }
let bar = (arg: number) => {
arg.toExponential()
}
// @ts-ignore
foo = bar
foo()
你有一个运行时错误,因为它是不安全的操作。
让我们回到您的示例,为了向useMemo
提供一些参数,您应该将它们作为useMemo
的第二个参数提供,如下所示:
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
请参阅文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.