【问题标题】:How to avoid having void in typescript如何避免打字稿出现空白
【发布时间】:2020-04-09 02:58:52
【问题描述】:

我正在使用 React 和 TypeScript。

import React from 'react';
import XLSX from 'xlsx';
interface PropsType {
  files: File
}
const ParsingFile:React.FC<PropsType> = ({files}) => {
  const [file, setFile] = useState(emptyFile);
  const [rfile, setRfile] = React.useState<XLSX.WorkBook>();
  const readFile = (file:File) =>{
    const reader = new FileReader();
    reader.onload = (e:any) => {
      const bstr = e!.target!.result;
      const wb = XLSX.read(bstr, {type: 'binary'});
      setRfile(wb);
    }
    reader.readAsBinaryString(file);
  }

  return(
     <div>
       {readfile(file)} // this line
     </div>
   )
}

这会引发错误,

Type 'void' is not assignable to type 'ReactNode'
The expected type comes from propeprty 'children' which is declared here on type
'DetailedHTMLProps<HTMLDivElement>, HTMLDivElement>'

如果我有的话,

<div>
  <React.Fragment>
    {readFile(file)}
  </React.Fragment>
</div>

它不会抛出错误。
这是我的问题,
1.为什么void函数不能单独使用?
2. 没有其他组件怎么解决?

提前致谢!
编辑
在这个组件(ParsingFile)中,我想要一个读取 excel 文件,解析和写入新的 excel 文件。

【问题讨论】:

  • 如果函数什么都不返回,为什么还要在 JSX 中调用呢?
  • 是的,readFile 如果你想在那里使用它,需要返回 JSX。到底想做什么?
  • 在 JSX 内部,我想进行“读取 excel 文件”的过程。
  • JSX 用于渲染 HTML。如果你的函数没有渲染任何东西,那么它的位置肯定不在模板内。您可以在 render 函数中调用它,但不要将其包含在模板中。
  • 我建议您将这种代码移到一个单独的模块中,该模块仅公开使用方法,而不是将其与 UI 相关代码混合。

标签: javascript reactjs typescript


【解决方案1】:

readFile 方法似乎只需要运行一次,并且要在组件初始化时运行?在这种情况下,我会建议你充分利用 react hooks。

useEffect 钩子中的第二个参数接受一个空数组,它“告诉”你的组件效果不依赖于任何其他值,并且永远不需要重新渲染。您可以通过 here 阅读更多关于这种常见的 React Hook 优化技术的信息。

const ParsingFile:React.FC<PropsType> = ({files}) => {
  const [file, setFile] = useState(emptyFile);
  const [rfile, setRfile] = React.useState<XLSX.WorkBook>();

  useEffect(() => {
   readFile(file);
  }, []);

   const readFile = (file:File) =>{
    const reader = new FileReader();
    reader.onload = (e:any) => {
      const bstr = e!.target!.result;
      const wb = XLSX.read(bstr, {type: 'binary'});
      setRfile(wb);
    }
    reader.readAsBinaryString(file);
  }

  return(
     <div>
        // other content
     </div>
   )
}

【讨论】:

  • 澄清一下,通过使用useEffect()readFile 将被挂载到组件上,对吧?所以,我不需要把它放在 JSX 中
  • @jayko03 没错。它将在挂载时运行(上述技术类似于componentDidMount)。
猜你喜欢
  • 2011-12-12
  • 2018-10-18
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2016-12-26
  • 1970-01-01
  • 2019-02-09
  • 1970-01-01
相关资源
最近更新 更多