【问题标题】:state data type of array in hooks, continue is initalized钩子中数组的状态数据类型,继续初始化
【发布时间】:2019-08-09 08:34:14
【问题描述】:

我尝试通过 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([]);

?

【问题讨论】:

    标签: typescript react-native react-hooks


    【解决方案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 的变量。这是常用的使用方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      • 2021-06-29
      • 2019-04-12
      相关资源
      最近更新 更多