简体   繁体   English

在 Next.js SSR 上使用 FileReader?

[英]Using FileReader on Next.js SSR?

I've got a Next.js app, and I am trying to use FileReader to read the contents of an 'uploaded' file.我有一个 Next.js 应用程序,我正在尝试使用 FileReader 读取“上传”文件的内容。

My component looks like below:我的组件如下所示:

  let fileReader;
  let props = {
    multiple: false,
    onRemove: file => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: file => {
      setFileList($ => [file]);
      fileReader.readAsText(file);
      return false;
    },
    fileList,
  };

  useEffect(() => {
    fileReader = new FileReader();

    fileReader.onload = event => {
      setFileData(JSON.parse(event.target.result));
    };

    setReady(true);
  }, []);

My upload form calls props.beforeUpload to pass the file to it, however the issue I have is that fileReader is undefined at this point.我的上传表单调用props.beforeUpload将文件传递给它,但是我遇到的问题是此时 fileReader 未定义。

I'm suspecting this is because of what's rendered server side and what's rendered client side, however I'm not sure how to handle this?我怀疑这是因为服务器端渲染了什么,客户端渲染了什么,但是我不确定如何处理这个问题?

I don't know what you suspect is correct but if you really think that server side rendering has broken it, then you could use dynamic import of next and use ssr:false to make it render on the client side only, more info我不知道你怀疑什么是正确的,但如果你真的认为服务器端渲染已经破坏了它,那么你可以使用 next 的动态导入并使用ssr:false使其仅在客户端呈现, 更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM