挂钩中数组的状态数据类型,继续初始化

时间:2019-08-09 08:34:14

标签: typescript react-native react-hooks

我尝试通过RNFS.readDir获取setState文件数据

但是当我设置数据时,状态被初始化。

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])

        })
      })
  }, [])
}

我希望追加到数据状态数组。 但已初始化。

然后,我可以像这样设置stateData的类型

const [documents, setDocuments] = React.useState([]);

1 个答案:

答案 0 :(得分:1)

你为什么不尝试这个?

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的变量。这是常见的使用方式。