我尝试过 setState 文件数据由 RNFS.readDir 获取
但是当我设置数据时,状态被初始化了。
interface fileUnit {
type: string,
index: number,
title: string,
path: string,
date: string,
size: number,
thumbnail: string
}
...
export const Documents = () => {
const hookState = React.useState([])
const documents: fileUnit[] = hookState[0]
const setDocuments: any =hookState[1]
React.useEffect(() => {
RNFS.readDir(RNFS.DocumentDirectoryPath)
.then(async (results: any[]) => {
results.map((file, key) => {
const fileUnit: fileUnit= { type: file.isFile()? 'file': 'folder', index: key, title: file.name, path: file.path, date: file.mtime, size: file.size, thumbnail: ''}
setDocuments([...documents, fileUnit])
})
})
}, [])
}
我希望附加到数据状态数组。 但它是初始化的。
那么,我可以像这样设置状态数据的类型
const [documents, setDocuments] = React.useState([]);
?
你为什么不试试这个呢?
export const Documents = () => {
const hookState = React.useState([])
const documents: fileUnit[] = hookState[0]
const setDocuments: any =hookState[1]
React.useEffect(aaync () => {
const results: any[] = await RNFS.readDir(RNFS.DocumentDirectoryPath)
const resfileUnit: fileUnit = results.map((file, key) => {
return { type: file.isFile()? 'file': 'folder', index: key, title: file.name, path: file.path, date: file.mtime, size: file.size, thumbnail: ''}
})
setDocuments([...documents, resfileUnit])
}, [])
}
你可以像你问的那样定义setState
变量。 这是常用的使用方式。