关于javascript:添加表格行时React ‘this’ undefined | 珊瑚贝

React ‘this’ undefined when adding table row


我正在尝试向表中添加新的数据行,当用户在字段中输入文本并单击按钮时会出现这种情况。
单击按钮与一个函数 (AddNewRow) 相关联,该函数将数据发送到控制器,然后将新行添加到包含数据的表中。

数据被正确发送到控制器,如果页面被刷新,新行就会显示(因为挂载后的 get 请求),但问题是表没有动态更新。

我在 AddNewRow 函数中不断收到控制台错误提示”这是未定义的”。
我尝试使用 ‘.bind(this)’ 和 AddNewRow() => {} 将 \\’this\\’ 绑定到构造函数,但它仍然没有绑定?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class App extends React.Component {
constructor() {
    super();

    this.state = {
        tableData: [{            
        }],        
    };      
  }  

   componentDidMount() {
    axios.get(‘/Jobs/GetJobs’, {
        responseType: ‘json’
    }).then(response => {        
        this.setState({ tableData: response });
    });
}

AddNewRow(){

    axios.post(‘/Controller/CreateJob’, { Name: this.refs.NewJobName.value})
        .then(function (response){              
            if(response.data.Error) {                  
                window.alert(response);
            }
        else {
                var data = this.setState.tableData;
                this.setState.tableData.push(response);
                this.setState({ tableData: data });
            }
        })}

    render() {
    const { tableData } = this.state;
    return (
       
        <button onClick={() => this.AddNewRow()} >ADD</button>
        <input ref=“NewJobName” type=“text” placeholder=“Name” />
        <ReactTable
        data={tableData}
         />
       
       )
    }


使用箭头函数使 this 在 then 函数中可用:

1
2
3
4
5
6
7
8
9
10
11
axios
  .post(‘/Controller/CreateJob’, { Name: this.refs.NewJobName.value })
  .then((response) => {
    if (response.data.Error) {
      window.alert(response);
    } else {
      this.setState(prevState => ({
        tableData: prevState.tableData.concat([response])
      }));
    }
  });

  • 嗯,好的,这解决了”这个”问题,但现在它告诉我”this.setState.tableData is undefined”?
  • 您可能打算访问 this.state.tableData,但无论如何您都不应该直接改变您的状态。查看我更新的代码。
  • 啊,我以前没有使用过’prevState’。谢谢,太好了,感谢您的帮助!


来源:https://www.codenong.com/50284049/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_8878.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?