gpt4 book ai didi

reactjs - 类组件中的 React.useMemo

转载 作者:行者123 更新时间:2023-12-03 16:54:49 25 4
gpt4 key购买 nike

在类组件的情况下,有没有办法使用这个钩子(Hook)或 React API 的一些类似物?
我想知道,我应该在类组件的情况下使用一些第三方备忘录助手(例如 lodash memo memoizeOne 等)还是存在一些官方 react 类组件的 API 方式。
谢谢你的帮助。
附言
我想在更改 child 的情况下生成 uuid。
使用 SFC 组件,我可以像这样使用 useMemo

const keyValue = useMemo(() => uuid()(), [children])
但是如何在没有任何第三方的情况下为基于类的组件实现相同的功能等。
附言我没有使用 Redux 等。只有纯 React.js

最佳答案

根据 React docs :

If you want to re-compute some data only when a prop changes, use a memoization helper.



文档使用 memoizeOne 作为图书馆,这将是一个不错的选择。您也可以更改 keyValue作为 componentDidUpdate 的副作用的一部分:
componentDidMount() {
this.keyValue = uuid()()
}

componentDidUpdate(prevProps) {
if (this.props.children !== prevProps.children) {
this.keyValue = uuid()()
// alternative: store keyValue as state to trigger re-render
}
}
getDerivedStateFromProps可以作为罕见情况的替代方案,其他选项 are usually preferred .

为什么 useMemo uuid() 不是一个好的选择

You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. (docs)



内存值 const keyValue = useMemo(() => uuid()(), [children])尽管 children 可能会重新计算在 React future 也一样。这种情况可能会导致不一致,如果 uuid()返回一个新的 id,但是 children没有改变。

对于功能组件,另一种选择是 useRefuseEffect取决于您的用例。

关于reactjs - 类组件中的 React.useMemo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61930571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com