背景
我正在编写的 React 应用程序出现问题。我一直在尝试从表中删除一行,但我一直在
setState 未定义
所以基本上这就是我的设置方式。
此函数将从表中删除该行。我没有测试过这个,因为我一直在
错误
setState
未定义
.
function removeRow(id) {
this.setState(state => {
state.tableData.splice(id, 1);
return {tableData: state.tableData};
});
}
问题
How do I correctly remove the tr
from the table
when the onClick method
fires of so that the state
will change and render
table
再次没有 tr
被删除了吗?
例子
这是调用 removeRow()
的 onClick
方法。
<td><a href="#" onClick={() => { removeRow(tableData[key].id) }}>Delete</a></td>
这就是一切看起来的样子,
var requests = [
{"id":1, "title":"Request from Nancy","updated_at":"2015-08-15 12:27:01 -0600","created_at":"2015-08-12 08:27:01 -0600","status":"Denied"}
]
class TableDisplay extends React.Component {
constructor() {
super();
this.state = {
tableData: requests
}
}
render() {
const {tableData} = this.props;
return (
<div className="table-wrapper">
<div><table className="table">
<tr className="separate"><td>Title</td><td>Status</td>
<td>Created</td><td>Updated</td><td>Delete</td></tr>
{Object.keys(tableData).map(function(key) {
function removeRow(id) {
this.setState(state => {
state.tableData.splice(id, 1);
return {tableData: state.tableData};
});
}
return // removed extra code to make it easy to read.
<td><a href="#" onClick={() => { removeRow(tableData[key].id) }}>Delete</a></td>
</tr>;
})}
</table>
</div>
</div>
);
}
}
我还尝试将 removeRow()
直接移动到 --- constructor
和 --- 之上,然后在 render()
之上移动
removeRow 未定义。
class TableDisplay extends React.Component {
constructor() {
super();
this.state = {
tableData: requests
}
}
// I have to remove "function" from the declaration or the app wont render from parse error.
removeRow(id) {
this.setState(state => {
state.tableData.splice(id, 1);
return {tableData: state.tableData};
});
}
render() {
const {tableData} = this.props;
return (
<div className="table-wrapper">
<div><table className="table">
<tr className="separate"><td>Title</td><td>Status</td>
<td>Created</td><td>Updated</td><td>Delete</td></tr>
{Object.keys(tableData).map(function(key) {
return // removed extra code to make it easy to read.
<td><a href="#" onClick={() => { removeRow(tableData[key].id) }}>Delete</a></td>
</tr>;
})}
</table>
</div>
</div>
);
}
}
原文由 wuno 发布,翻译遵循 CC BY-SA 4.0 许可协议
您的组件存在一些问题,即您没有在删除函数中绑定上下文(因此
setState
未定义)。尝试这样的事情: