【发布时间】:2020-03-06 04:52:33
【问题描述】:
我是 React 的新手,并且从我拥有的后端服务器接收到的 JSON 创建了一个动态表。对于每个表格行,我都有一个按钮,该按钮打开一个下拉菜单,该下拉菜单有两个选项 - 编辑行中的信息和删除行。我为下拉按钮制作了一个单独的组件,目前正在将行的 ID 传递给它。 使用当前代码,我可以删除该行,但只能在刷新页面时看到更改。我已经查看了其他问题的答案,例如我的问题,有人说需要更新状态,但我对在这种情况下如何处理感到困惑。
编辑:我没有使用任何东西来管理状态。只是简单的 React
这是被渲染的表格的代码:-
<table className="table">
<thead>
<tr>
<th>S. NO.</th>
<th>NAME</th>
<th>AGE</th>
<th>ADDRESS</th>
<th></th>
</tr>
</thead>
<tbody>
{this.state.personData.map((Row, idx) => (
<tr key={Row.id}>
<td>{idx + 1}</td>
<td>{Row.name}</td>
<td>{Row.age}</td>
<td>{Row.addr}</td>
<td>
{" "}
<DropDownButton id={Row.id} />{" "}
</td>
</tr>
))}
</tbody>
</table>
这是 DropDownButton 组件中的代码:-
handleDelete() {
console.log("ID " + this.props.id);
fetch("http://localhost/person/" + this.props.id, {
method: "DELETE",
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type"
}
})
.catch(error => console.log("Error:", error))
.then(response => console.log("Success:", response));
}
render() {
return (
<React.Fragment>
<div className="dropdown">
<button
type="button"
className="btn dropdown-toggle dropdownButton"
data-toggle="dropdown"
>
OPTIONS
</button>
<div className="dropdown-menu">
<p className="dropdown-item" onClick={this.handleEdit}>
EDIT
</p>
<p className="dropdown-item" onClick={this.handleDelete}>
DELETE
</p>
</div>
</div>
</React.Fragment>
);
}
}
【问题讨论】:
-
在
.then(response)块内的handleDelete()函数内,试试.then(response => { this.setState({personData : response}) }如果响应是您的新数组数据,那么它将起作用.. -
@ManirajMurugan 实际上问题在于原始数据数组 personData 位于将每一行的 ID 传递给 DropDownButton 组件的父组件中。如何将此数据变量传递给 DropDownButton 组件?
-
您可以在表格组件中传递
<DropDownButton persons={this.state.personData} id={Row.id} />之类的数据,在下拉按钮组件中您可以得到它,例如this.props.persons.. -
@ManirajMurugan 使用这种方法我得到一个 'TypeError:Cannot assign to read only property'
-
你到底在哪里得到这个错误??在哪个文件和变量中??
标签: reactjs