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 = { componentDidMount() { AddNewRow(){ axios.post(‘/Controller/CreateJob’, { Name: this.refs.NewJobName.value}) render() { |
使用箭头函数使 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/