【问题标题】:ReactJS: How to filter an array in JavaScript to show specific image on mapReactJS:如何在 JavaScript 中过滤数组以在地图上显示特定图像
【发布时间】:2026-02-03 15:40:02
【问题描述】:

我正在使用AISHub APIs 构建一个船只可视化器。查询 API 后,我可以获得一个包含我感兴趣的容器的 json 文件,并将这些容器注入到一个表格中,如下所示:

在打印屏幕上显示的表格中有 16 艘船,但它们来自不同的公司。显示的徽标数量正好是 16,就像表格的行数一样。

问题是我只看到一个徽标,而不是桌面上所有其他公司的徽标(因此在 google-map 上)。

我已经准备了一个关联图,可以在下面的代码中看到:

ShipTracker.js

import donjonImage from '../logos/donjon.jpg';
import dutraImage from '../logos/dutra.png';
import glddImage from '../logos/greatlakesdredgeanddock.png';

const shipCompanyMap = {
  Michigan: 'DONJON',
  STUYVESANT: 'DUTRA',
  Ellis_Island: 'GREATLAKESDREDGEANDDOCK'
};

const companyImageMap = {
  DONJON: donjonImage,
  DUTRA: dutraImage,
  GREATLAKESDREDGEANDDOCK: glddImage,
};

const associationMap = Object.values(shipCompanyMap).reduce(
  (acc, curr) => ({
    ...acc,
    [curr]: companyImageMap[curr]
  }),
  {}
);


const Ship = ({ ship }) => {
  const shipName = ship.NAME;
  const company = shipCompanyMap[shipName];
  const shipImage = companyImageMap[company];

  return (
    <div>
      <img src={glddImage} alt="Logo" /> // <-- I think loop should go here?
    </div>
  );
};
export { Ship };

const ShipTracker = ({ ships }) => {
  const handleRowClick = (rowValue) => {
    console.log(rowValue);
  };
  return (
    <div className="ship-tracker">
      <Table className="flags-table" responsive hover>
        <thead>
          <tr>
            <th>#</th>
            <th>Name</th>
            <th>Callsign</th>
            <th>Heading</th>
            <th>SOG</th>
            <th>IMO</th>
            <th>MMSI</th>
            <th>Longitude</th>
            <th>Latitudee</th>
          </tr>
        </thead>
        <tbody>
          {ships.map((ship, index) => {
            const { IMO, NAME, CALLSIGN, HEADING, SOG, MMSI, LONGITUDE, LATITUDE } = ship;
            const cells = [ NAME, CALLSIGN, HEADING, SOG, IMO, MMSI, LONGITUDE, LATITUDE ];
            return (
              <tr onClick={() => handleRowClick(ship)} key={index}>
                <th scope="row">{index}</th>
                {cells.map((cell) => <td>{cell}</td>)}
              </tr>
            );
          })}
        </tbody>
      </Table>
    </div>
  );
};

export default ShipTracker;

GoogleMap.js 文件中是我呈现徽标的位置以及(我认为)我应该操作过滤或搜索以确保徽标对应于显示在地图显示:

import { Ship } from '../components/ShipTracker';

class BoatMap extends Component {
    constructor(props) {
        super(props);
        this.state = {
            buttonEnabled: true,
            buttonClickedAt: null,
            progress: 0,
            ships: []
        };
        this.updateRequest = this.updateRequest.bind(this);
        this.countDownInterval = null;
    } 

    // Other operations.....

    render() {
        return (
            <div className="google-map">
                <GoogleMapReact
                    bootstrapURLKeys={{ key: 'My_KEY' }}
                    center={{
                        lat: 42.4,
                        lng: -71.1
                    }}
                    zoom={8}
                >
                    {this.state.ships.map((ship) => (    // <-- maybe the filter function here?
                        <Ship ship={ship} key={ship.CALLSIGN} lat={ship.LATITUDE} lng={ship.LONGITUDE} />
                    ))}


                </GoogleMapReact>
            </div>
        );
    }
}

到目前为止我做了什么:

1) 这是一个循环问题。我试图循环通过提供的 API 提取的公司,并尝试将该公司与其徽标匹配并将其显示在谷歌地图上,但我不确定如何组织循环,因为我只看到一个徽标而不是更多。

2) 在做了一些研究之后,我发现了filtering function 并尝试使用 bit 来遍历一组徽标。

3)我认为this post正是我想要的,并在研究如何使用它后尝试申请。但是我仍然无法遍历一个数组并将每个公司分配给它的徽标。

感谢您指出解决此问题的正确方向。

【问题讨论】:

    标签: javascript html reactjs


    【解决方案1】:

    如果我理解正确,这里的问题是您的&lt;Ship /&gt; 组件中的徽标图像渲染需要是动态的。目前它是静态的,并且被“硬编码”到glddImage 图像中,这就是为什么只显示一个徽标的原因。

    假设&lt;Ship /&gt;ship.NAME 的值是"Michigan""STUYVESANT""Ellis_Island" 中的任何一个,那么以下更新应该会完成您的实现:

    const Ship = ({ ship }) => {
      const shipName = ship.NAME;
      const company = shipCompanyMap[shipName];
    
      /* Optional */
      const defaultFallbackImage = "../path/to/image-not-found-placeholder.png"
    
      /* Use fallback image if no company image found */
      const shipImage = companyImageMap[company] || defaultFallbackImage;
    
      return (
        <div>
          {/* Render shipImage image */}
          <img src={shipImage} alt="Logo" />
        </div>
      );
    };
    
    export { Ship };
    

    【讨论】:

    • 您完全理解我的问题,感谢您的帮助我解决了它!!! :) 非常感谢!!
    【解决方案2】:

    看起来您正在为您的Ship 定义中的每艘船设置src,您将其设置为glddImage。这不是动态的,并且将为每艘船产生相同的结果。您仅在完成此操作之后尝试通过您的船只阵列进行映射。这可以通过在Ship 的定义映射您的徽标源来解决。

    【讨论】:

      最近更新 更多