react-useDefferredValue

1 min read
Table of Contents

主要作用

我们可以使用useDefferredValue来避免同步渲染造成的页面阻塞

tsx
import { useDeferredValue, useState } from 'react'
import { Flex, Input, List } from 'antd'
import mockjs from 'mockjs'
interface Item {
name: string
id: number
address: string
}
function App() {
const [inputValue, setInputValue] = useState('')
const [list] = useState<Item[]>(() => {
return mockjs.mock({
'list|1000': [
{
'id|+1': 1,
name: '@natural',
address: '@county(true)',
},
],
}).list
})
const deferredQuery = useDeferredValue(inputValue)
const isStale = deferredQuery !== inputValue
const findItem = () => {
console.log(deferredQuery, '----', inputValue)
return list.filter((item) => item.name.toString().includes(deferredQuery))
}
return (
<div>
<Flex>
<Input
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="请输入姓名"
/>
</Flex>
<List
style={{ opacity: isStale ? 0.5 : 1.0, transition: 'opacity 0.8s ease-in-out' }}
renderItem={(item) => (
<List.Item>
<List.Item.Meta title={item.name} description={item.address} />
</List.Item>
)}
dataSource={findItem()}
/>
</div>
)
}
export default App

后记

My avatar

感谢你读到这里。

这座小站更像一份持续维护的“终端笔记”:记录我解决问题的过程,也记录走过的弯路。

如果这篇内容对你有一点点帮助:

  • 点个赞 / 收藏一下,方便你下次回来继续翻
  • 欢迎在评论区补充你的做法(或者指出我的疏漏)
  • 想持续收到更新:可以订阅 RSS(在页面底部)

我们下篇见。


More Posts

评论

评论 (0)

请先登录后再发表评论

加载中...