反应 - 设置状态并同时获取值

时间:2016-01-07 20:11:20

标签: javascript reactjs

我正在使用React制作ToDo应用程序。我有以下数据:

getInitialState: function(){
    return {
        name:"Michael",
        tasks:[
            {task:"Go to the gym", completed:false, id:1 }, 
            {task:"Do yoga", completed:false, id:2 },
            {task:"Buy groceries", completed:true, id:3 },
            {task:"Get tire fixed", completed:true, id:4}
        ],
        numCompleted:null
    }
},

如何在初始状态下显示numCompleted的值?在实例化之前我无法计算它。

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

怎么样:

getInitialState: function(){
    var tasks = [
        {task:"Go to the gym", completed:false, id:1 }, 
        {task:"Do yoga", completed:false, id:2 },
        {task:"Buy groceries", completed:true, id:3 },
        {task:"Get tire fixed", completed:true, id:4}
    ];
    return {
        name:"Michael",
        tasks:tasks,
        numCompleted:tasks.filter(function(task) {
            return task.completed;
        }).length
    }
},

如果你想要,你可以计算它......

答案 1 :(得分:0)

你能否按以下方式计算:

getInitialState: function(){

   var _tasks = [{task:"Go to the gym", completed:false, id:1 }, 
           {task:"Do yoga", completed:false, id:2 },
           {task:"Buy groceries", completed:true, id:3 },
           {task:"Get tire fixed", completed:true, id:4}];

  var completedCount = 0;

  for( var i = 0; i < tasks.length; i++ ) {
     if ( task[i].completed ) {
        completedCount++;
     }
  }

   return {
       name:"Michael",
       tasks:_tasks,
       numCompleted: completedCount
   }

},

答案 2 :(得分:0)

由于这是一个“计算”属性,无论何时状态发生变化都会改变,为什么不在组件的render中执行此操作?

getInitialState: function(){
    return {
        name:"Michael",
        tasks:[
            {task:"Go to the gym", completed:false, id:1 },
            {task:"Do yoga", completed:false, id:2 },
            {task:"Buy groceries", completed:true, id:3 },
            {task:"Get tire fixed", completed:true, id:4}
        ]
    }
    render: function () {
      let numCompleted = this.state.tasks.reduce(function (completed, task) {
        return completed + task.completed ? 1 : 0;
      }, 0);

      // render tasks
    }
},