【问题标题】:Get only the first element of a map仅获取地图的第一个元素
【发布时间】:2021-12-05 21:28:18
【问题描述】:

我有以下代码,其目的是在另一个组件中重复使用,并根据我的对象的 id 和我的 API 返回给出不同的链接。

问题在于,我使用地图功能的方式是在屏幕上多次复制同一个按钮。我想知道我如何只得到一个按钮。我可以在该地图中以某种方式使用 indexOf 吗? 其他一切正常

    const ButtonGroup = (linksReturn) => {
      return linksReturn.map((urlAdress, index) => (
        <div key={index}>
            <button
              target="_blank"
              href={urlAdress["detailsUrl"]}
            >
              Acess Link
            </button>
          </div>
      ));
    };
    const PreviewActions = ({ linksReturn }) => {
      return <div>{ButtonGroup(linksReturn)}</div>;
    };
    export default PreviewActions;

这是我重用按钮的代码部分

    import { useEffect } from 'react';
    import { useParams } from 'react-router-dom';
    import PreviewActions from './PreviewActions';

    // ** Store & Actions
    import { getInfo } from '../store/actions/index';
    import { useDispatch, useSelector } from 'react-redux';


    const LicitacaoPreview = () => {
      const dispatch = useDispatch();
      const store = useSelector((state) => state.allInfo);

      const { id } = useParams();
      
      useEffect(() => {
        dispatch(getInfo(id));
      }, [dispatch]);

      return typeof store.lotesData === 'object' ? (
        <div>
              <PreviewActions
                id={id}
                linksReturn={store.infoData}
              />
        </div>
      ) 
    };

    export default LicitacaoPreview;

【问题讨论】:

    标签: javascript reactjs dictionary for-loop indexof


    【解决方案1】:

    Array.prototype.map() 不是这样工作的,它调用作为参数传入的函数对每个单个数组元素并返回结果数组。

    更好的方法是使用Array.prototype.slice() 返回原始数组的特定部分,然后在其上使用map()

    const ButtonGroup = (linksReturn) => {
        const newArr = linksReturn.slice(startindex, endindex); // replace with your index appropriately
        return newArr.map((urlAdress, index) => (
            <div key={index}>
                <button
                    target="_blank"
                    href={urlAdress["detailsUrl"]}
                >
                    Acess Link
                </button>
            </div>
        ));
    };
    

    【讨论】:

    • 非常感谢,对我帮助很大!
    • 没问题很乐意帮忙
    猜你喜欢
    • 2021-05-16
    • 2012-07-21
    • 2011-03-13
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多