React JSX:锚标记数组中的href路径引用循环中的最后一个路径

时间:2017-04-26 02:54:00

标签: javascript reactjs jsx

我正在尝试生成一个锚标记数组,每个锚标记都有不同的href值。我遇到的问题是每个锚标记的路径与for循环结束时的路径相同。我应该如何修改我的代码,以便路径不是都引用循环中路径的最后一个值?

这是我的代码:

  function generateLinks(){
    let path = '/';
    let links = [ <a href={ path }>root</a> ];
    for (let link = 0; link < 5; link++){
      const partial =  "folder"+ link;
      path += partial + '/'
      links.push(<a href={ path }>{ partial }</a>);
    }
   return links;
 }

目前这个输出:

[<a href='/folder0/folder1/folder2/folder3/folder4/'>root</a><a href='/folder0/folder1/folder2/folder3/folder4/'>folder0</a><a href='/folder0/folder1/folder2/folder3/folder4/'>folder1</a><a href='/folder0/folder1/folder2/folder3/folder4/'>folder2</a><a href='/folder0/folder1/folder2/folder3/folder4/'>folder3</a><a href='/folder0/folder1/folder2/folder3/folder4/'>folder4</a>]

我想要的输出是:

[<a href='/'>root</a><a href='/folder0/'>folder0</a><a href='/folder0/folder1/'>folder1</a><a href='/folder0/folder1/folder2/'>folder2</a><a href='/folder0/folder1/folder2/folder3/'>folder3</a><a href='/folder0/folder1/folder2/folder3/folder4/'>folder4</a>]

2 个答案:

答案 0 :(得分:2)

您发布的代码正常运行。您的真实代码必须与众不同。这是一个jsfiddle,显示它具有正确的href值:https://jsfiddle.net/8d2xLc9L/

 function generateLinks(){
    let path = '/';
    let links = [ <a href={ path }>root</a> ];
    for (let link = 0; link < 5; link++){
      const partial =  "folder"+ link;
      path += partial + '/'
      links.push(<a href={ path }>{ partial }</a>);
    }
   return links;
 }

 document.getElementById("container").textContent = JSON.stringify(generateLinks(), null, 2);

答案 1 :(得分:1)

那是真的,你的逻辑很有效!

也许你在JSX中循环数组的方式有问题?以上工作对我有用:

import React, {Component} from 'react';

export default class MyApp extends Component {

  constructor(props){
    super(props);
  }

  generateLinks(){
    let path = '/';
    let links = [ <a href={ path }>root</a> ];
    for (let link = 0; link < 5; link++){
      const partial =  "folder"+ link;
      path += partial + '/'
      links.push(<a href={ path }>{ partial }</a>);
    }
    return links;
  }

  render(){
    return <div>{this.generateLinks()}</div>;
  }

}