简体   繁体   English

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

[英]React - Set State and get value simultaneously

I am making a ToDo App with React. 我正在用React制作ToDo应用。 I have the following data: 我有以下数据:

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
    }
},

How can I get the value of numCompleted to be shown in the initial state? 如何获取numCompleted的值以在初始状态下显示? I cannot calculate it before it is instantiated. 我无法在实例化之前对其进行计算。

Thanks for the help. 谢谢您的帮助。

How about: 怎么样:

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
    }
},

You can just calculate it if you want... 您可以根据需要进行计算...

Can you not just calculate that in the following manner: 您是否可以仅通过以下方式进行计算:

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
   }

}, },

Since this is a "computed" property, that will change whenever state changes anyway, why not just do this in your component's render ? 由于这是一个“计算”属性,无论状态如何变化,该属性都会发生变化,为什么不在组件的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
    }
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM