javascript - 循环内声明的变量保留先前的值

标签 javascript reactjs react-router

几个小时以来我一直在尝试自己解决这个问题,现在我举手看看是否有人有任何想法。

问题

我正在制作一个动态侧边栏过滤器,它迭代 groups 属性并返回带有查询属性的 Link 来更新路由器。将显示一个复选框,并根据当前是否排除该组 ID 进行标记。

代码

render: function() {
  return (
    <ul>
    {this.props.query.filter == 'connections' ?
     // the array of groups to build the filter for
     this.props.groups.map(function (group) {
     // this array would start with the currently excluded ids, and end with the new list of ids
     var new_ids = this.context.router.getCurrentQuery().exclude || [];
     var index = new_ids.indexOf(group.id.toString());
     console.log('my id: ' + group.id);
     console.log('starting: ' + new_ids);
     // again, the array is excluded ids, so if it's not in the array it should be checked
     var selected = index == -1;
     if (selected) {
       // if this link is clicked, add the id to the excludes
       new_ids.push(group.id);
     }
     else {
       // if this linked is clicked, remove the id from the excludes
       new_ids.splice(index, 1);
     }
     console.log('ending: '+new_ids);
     // return the preloaded link
     return <Link  key={group.name}
                   to="feed"
                   query={{filter: 'connections', exclude: new_ids}}>
              <small>{group.name}</small>
            </Link>;
      }, this) : null }
   </ul>
);

当我使用 input type="checkbox" 和带有 this.transitionTo 的事件处理程序时,这有效,但我想使用 Link code> 组件来处理请求而不是事件处理程序。

结果

该页面在第一次点击时工作正常(query.exclude == undefined),但之后 new_ids 会随着每次迭代而发生变化。 这是控制台输出...

id: 11
starting: 
new ids: 11
id: 6
starting: 
new ids: 6
id: 21
starting: 
new ids: 21

单击其中一个后(例如第一组 - id 11,它会困惑)...

id: 11
starting: 11
new ids: // this is correct, it removes 11 from the list
id: 6
starting: // this should be 11, instead its inheriting the prior value
new ids: 6 // this should be 11, 6
id: 21
starting: 6 // this should be 11, instead its inheriting the prior value
new ids: 6,21 // this should be 11, 21

我尝试将此迭代设为 for ... 循环 而不是 .map() 但这没有帮助。我还将最初的 excepted_ids 移出迭代,但结果又相同。

同样,这一切应该做的就是根据单击链接的结果生成用于导航的 query.exclude 属性的值。

任何有关可能发生的事情的想法将不胜感激。谢谢。

最佳答案

以下是避免改变 exclude 数组的方法。

render: function() {
  return (
    <ul>
    {this.props.query.filter == 'connections' ?
     // the array of groups to build the filter for
     this.props.groups.map(function (group) {
     // this array would start with the currently excluded ids, and end with the new list of ids
     var new_ids = this.context.router.getCurrentQuery().exclude || [];
     console.log('my id: ' + group.id);
     console.log('starting: ' + new_ids);
     
     var found = false;
     new_ids = new_ids.filter(function(exclude){
         if(exclude != group.id.toString()){
            return true;
         } else {
            found = true;
            return false;
         }
     });

     if(!found) {
        new_ids.push(group.id);
     } 
     //new_ids now has a copy of the exclude array with the values excluded.

     console.log('ending: '+new_ids);
     // return the preloaded link
     return <Link  key={group.name}
                   to="feed"
                   query={{filter: 'connections', exclude: new_ids}}>
              <small>{group.name}</small>
            </Link>;
      }, this) : null }
   </ul>
);

Array.prototype.filter 基本上遍历数组并检查每个元素。如果返回值为true,它将添加到新数组,否则正在迭代的元素将被丢弃。

这是一个以类似方式工作的非 react 脚本。

var group = [1,2,3,4,5,6,7,8,9,10,11];
var excluded = [11];
var results = document.getElementById('results');

group.forEach(function(group){
    var new_ids = excluded;
    results.innerHTML += 'my id: ' + group + '\n';
    results.innerHTML += 'starting: ' + new_ids + '\n';
  
    var found = false;
    new_ids = new_ids.filter(function(exclude){
       if(exclude != group){
           return true;
       } else {
           found = true;
           return false;
       }
    });
     
    if(!found){
        new_ids.push(group);
    }
    results.innerHTML += 'ending: ' + new_ids + '\n';
});
<pre id="results"></pre>

关于javascript - 循环内声明的变量保留先前的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32230875/

相关文章:

javascript - Xpath 单击 td 中的按钮,其中行包含特定文本值

javascript - Angular 2 本地存储

reactjs - 如何使用redux React调用另一个reducer方法

javascript - 如何在 react 中无限发送请求而不渲染整个组件以进行实时提要

javascript - 使用 reactjs 和 Material UI 单击按钮时更改内容

javascript - 如何翻译 react-router 路由路径

javascript - 从 AngularJS 将数据发送回 ASP.NET

javascript - 为什么我不能使用 ' instead of "作为 JSON 字符串?

javascript - Facebook Create React App Build - 添加图像作为 Prop 类型

reactjs - 如何使用闪存消息react-router 4进行重定向