首页 > 解决方案 > setting variables in a map function

问题描述

I have a function that returns this jsx mixed with some code like this:

showMedia = () => {

  return (
            <div>
                {
                    <div id="mainContent">
                        {props.files.map((file) =>
                            const ext = fileExtension(file.name),
                            const icon = fileIcon(ext),
                            const isImg = isImage(ext),
                            <div key={file.id}>
                                <DisplayResults
                                    fileId={file.id}
                                    downloadName={file.downloadName}
                                    fileTitle={file.title}
                                    isImg={isImg}
                                    icon={icon}
                                    ext={ext}
                                />
                            </div>
                        )}
                    </div>
                }
            </div>
         );
}

In my editor, it's saying that it is expecting an '{' for the const variables I am setting after .map

Am I not using the correct syntax?

Thanks!

标签: reactjsecmascript-6

解决方案


Since you don't have a function body {} for your arrow function, it is expecting an implicitly returned expression.

Give it a function body and declare your variables and return the JSX instead:

showMedia = () => {
  return (
    <div>
      {
        <div id="mainContent">
          {props.files.map(file => {
            const ext = fileExtension(file.name);
            const icon = fileIcon(ext);
            const isImg = isImage(ext);
            return (
              <div key={file.id}>
                <DisplayResults
                  fileId={file.id}
                  downloadName={file.downloadName}
                  fileTitle={file.title}
                  isImg={isImg}
                  icon={icon}
                  ext={ext}
                />
              </div>
            );
          })}
        </div>
      }
    </div>
  );
};

推荐阅读