简体   繁体   English

setState不是函数

[英]setState is not a function

I'm trying to add a delete button to the table so I can get el.id and delete it. 我试图将删除按钮添加到表中,以便可以获取el.id并将其删除。 I can't read el.id , so I wanted to add it to states. 我看不懂el.id ,所以我想将其添加到州。

Please tell me if there is another solution or if it can be fixed. 请告诉我是否还有其他解决方案,或者可以解决。

This is my code: 这是我的代码:

componentDidMount: function(){
       var url = 'I have an api here'

       axios.get(url).then(function(response){
         var arr = $.map(response.data, function(el) {
           $.each(el, function (i, word) {
             this.setState({el: el});
               $("#data").append(
                 '<tr><td>' + el.name + '</td><td>' + el.email + '</td><td>' + el.category + '</td><td>' + el.address + '</td><td>' + '<button onClick={console.log(el)} class="btn btn-primary">delete</button>'
               );
           });
         });
         $('body').addClass('stop-scrolling');
       })
  },

you're calling this.setState inside a callback function so this doesn't to the expected context. 您在回调函数中调用this.setState因此this与预期的上下文不符。

you can store the value of this inside a variable : 你可以的值存储this变量里面:

componentDidMount: function(){
   var url = 'I have an api here';
   var self = this;

   axios.get(url).then(function(response){
     var arr = $.map(response.data, function(el) {
       $.each(el, function (i, word) {
         self.setState({el: el});
         $("#data").append('<tr><td>' + el.name + '</td><td>' + el.email + '</td><td>' + el.category + '</td><td>' + el.address + '</td><td>' + '<button onClick={console.log(el)} class="btn btn-primary">delete</button>');
       });
     });
     $('body').addClass('stop-scrolling');
   })
},

or you can use arrow function to solve your problem 或者您可以使用箭头功能解决您的问题

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

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