【问题标题】:Map and Switch in React JSXReact JSX 中的映射和切换
【发布时间】:2022-02-21 17:14:20
【问题描述】:

我有一点点泡菜,我有一个 React 函数组件,我需要在我的 JSX 中 mapswitch

我知道我应该尝试在 return 语句之外/之前执行此操作,但我似乎无法弄清楚,因为渲染的组件依赖于通过组件 props 传递的数组。

以下是我在退货声明中想要实现的目标

{(() => {
  files.map((file, index) =>
    let type = getFileType(file)
    switch(type){
      case 'image':
        return (
          <div className="item">
            <img src={file}/>
          </div>
        )
      default:
       return;
    }
  })()
}

我显然忽略了一些重要的事情,我已经做了一段时间了,但似乎无法理解。 任何帮助将不胜感激。

【问题讨论】:

  • 文件数组是什么样子的
  • 我看不出有什么明显的错误。请阅读How to Ask 并提供对问题 的清晰描述(而不是您想要实现的目标)和minimal reproducible example
  • 他们被称为Function Components。他们(通常)不是functional
  • 文件数组不是问题,但为了回答您的问题,它包含文件 URL 列表。一个例子是['http://example.com/image/png'],而getFileType 函数返回文件的类型,在本例中为image

标签: javascript reactjs switch-statement jsx


【解决方案1】:

您需要从立即调用函数中return。尝试如下。

{(() => {
  return files.map((file, index) => {
    let type = getFileType(file);
    switch (type) {
      case "image":
        return (
          <div className="item">
            <img src={file} />
          </div>
        );
      default:
        return null;
    }
  });
})()}

【讨论】:

  • 谢谢阿米拉,你的代码和我的一样。问题是,react 在let type = getFileType(file)switch(type){ 行上抛出错误。
  • Quatban Taco,我已经修复了语法问题,再次检查!
  • 您的更新不会引发另一个错误。这解决了我的问题,谢谢。
【解决方案2】:

这样的事情应该可以工作:

import React from "react";



const files = ["file01.img", "file02.other", "file03.img"];


const getFileType = (file) => {
    if (file.endsWith(".img")) return "image";
    return "other";
};



export default function YourComponent() {

    return (

        <div>

            { files.map( (file, index) => {
                
                let type = getFileType(file)
                
                switch (type) {
                    case 'image':
                        return (
                            <div className="item">
                                <p>image</p>
                            </div>
                        )
                    default:
                        return <p>other</p>
                }
                
            } )}

        </div>

    );

};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-15
    • 2020-09-25
    • 2021-09-27
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    相关资源
    最近更新 更多