【问题标题】:How can I map over two arrays at the same time?如何同时映射两个数组?
【发布时间】:2016-12-24 07:32:51
【问题描述】:

我有两个数组,一个带有 url,一个带有内容。 它们看起来像这样:

const link = [ 'www.test0.com', 'www.test1.com', 'www.test2.com' ]
const content = [ 'this is test0 content', 'this is test1 content', 'this is test2 content' ]

如何同时映射两个数组并在我新创建的元素中使用它们的值?

我需要将 url 的值用于我的 reactplayer,并将 content 的值用作播放器下方的文本。

所以它应该看起来像这样:

<Reactplayer url"link0" />
<ControlLabel>content0</ControlLabel>

这可能吗?什么是更好的设置方法?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    使用map的第二个参数,即当前元素的索引,可以访问第二个数组的正确元素。

    const link = [ 'www.test0.com', 'www.test1.com', 'www.test2.com' ];
    const content = [ 'this is test0 content', 'this is test1 content', 'this is test2 content' ]
    
    const players = link.map((value, index) => {
      const linkContent = content[index];
      return (
        <div>
          <Reactplayer url="{value}" />
          <ControlLabel>{linkContent}</ControlLabel>
        </div>
      );
    });
    

    这是 zip 方法的完美候选者,该方法可用于各种库,例如 LodashRambda,如果您的项目中有其中一个。

    const players = _.zip(link, content).map((value) => {
      return (
        <div>
          <Reactplayer url="{value[0]}" />
          <ControlLabel>{value[1]}</ControlLabel>
        </div>
      );
    });
    

    【讨论】:

      【解决方案2】:

      最好是这样:

      const data = [
          { link: "www.test0.com", text: "this is test0 content" },
          { link: "www.test1.com", text: "this is test1 content" }
      ];
      

      然后您将呈现如下内容:

      render() {
          var links = [];
          for (var i = 0; i < data.length; i++) {
              var item = data[i];
              links.push(<div><Reactplayer url={item.link}/><ControlLabel>{item.text}</ControlLabel></div>);
          }
      
          return (<div>{links}</div>);
      }
      

      请注意,这是未经测试的代码,因为我目前没有设置可以测试它的 JSX 项目。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 2021-03-10
      • 1970-01-01
      • 2019-05-14
      • 2021-07-04
      • 1970-01-01
      相关资源
      最近更新 更多