在 model 中创建获取历史记录api
在 model 的 Uploader 接口中添加 get 方法,用于查询 leancloud 历史记录
注意如果是被删除的图片则没有 url, 所以resolve时需要过滤:
resolve(images.filter((image: any) => image.attributes.url)))
const Uploader = {
add(file: any, filename: string) {
// ...
},
get(page = 0, limit = 10) {
const query = new Query('Image')
query.include('owner')
query.limit(limit)
query.skip(page * limit)
query.descending('createAt')
query.equalTo('owner', AV.User.current())
return new Promise((resolve, reject) => {
query
.find()
.then((images) => resolve(images.filter((image: any) => image.attributes.url)))
.catch((error) => reject(error))
})
},
}
创建 historyStore
```typescript import { message } from ‘antd’ import { makeObservable, observable, action } from ‘mobx’ import { Uploader } from ‘../models’
class HistoryStore { @observable list = [] @observable isLoading = false @observable hasMore = true @observable page = 0 limit = 10
constructor() { makeObservable(this) }
@action append(newList) { this.list = this.list.concat(newList) }
@action get() { this.isLoading = true Uploader.get(this.page, this.limit) .then((newList) => { this.append(newList) this.page++ if ((newList as any).length < this.limit) { this.hasMore = false } }) .catch((error) => { message.error(‘加载数据失败’) }) .finally(() => { this.isLoading = false }) } }
export default new HistoryStore()
<a name="SO0LJ"></a>
### 使用 antd 的 List 组件展示历史记录
安装 `react-infinite-scroll-component` 用于无限滚动
```bash
yarn add react-infinite-scroll-component
import { Button, Divider, List } from 'antd'
import { observer } from 'mobx-react'
import { useStore } from '../store'
import InfiniteScroll from 'react-infinite-scroll-component'
import { MutableRefObject, useEffect, useRef } from 'react'
import Loading from '../components/Loading'
import { handleCopy } from '../models'
const History: React.FC = observer(() => {
const { HistoryStore } = useStore()
const inputRef = useRef() as MutableRefObject<HTMLInputElement>
const loadMore = () => {
HistoryStore.get()
}
useEffect(() => {
loadMore()
// 组件卸载时清除本地记录
return () => HistoryStore.resetHistory()
}, [])
return (
<>
<InfiniteScroll
dataLength={HistoryStore.list.length}
next={loadMore}
loader={<Loading />}
hasMore={!HistoryStore.isLoading && HistoryStore.hasMore}
endMessage={<Divider plain>没有更多了 🤐</Divider>}
>
<List
dataSource={HistoryStore.list}
renderItem={(item: any) =>
item ? (
<List.Item key={item.id}>
{/* 列表信息省略 */}
</List.Item>
) : (
''
)
}
></List>
</InfiniteScroll>
</>
)
})
export default History
删除图片
只需要知道图片的 id 就可以删除
delete(id) {
const file = AV.File.createWithoutData(id)
file.destroy()
},