【发布时间】:2019-04-02 01:21:09
【问题描述】:
我是 ReactJS 的新手。在我当前的项目中,我正在将数据从 Mongo 数据库填充到 HTML 表中,并且我有一列带有复选框(根据 db 值动态创建)用于选择默认配置文件(见下图)。检查一个配置文件时,数据库中的特定配置文件将更新为 true 标志,而其他配置文件为 false
在复选框上单击它将调用 API 来更新 db 标志。更新数据库后,我需要调用一个 API 从同一个集合和更新表中获取数据。我正在使用以下代码。
我正在尝试使用 setState 来呈现新数据而不刷新页面。我想我在没有更好理解的情况下使用 setState,我需要澄清这一点。我的问题是下面的代码有什么问题,除了使用 setState 之外还有什么更好的方法来实现这种情况?
Profiles.jsx - 渲染()
render() {
return (
<React.Fragment>
<div>
<table className="table">
<thead className="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Create Date</th>
<th scope="col">Last Updated Date</th>
<th scope="col">Default Profile</th>
<th scope="col">Update</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
{this.state.profilesData.map(prof => (
<tr key={prof._id}>
<th scope="row">{prof._id}</th>
<td>{prof.createdDate}</td>
<td>{prof.lastUpdatedDate}</td>
<td align="center">
{prof.defaultProfile === true ? (
<input
name="defaultProfileCheck"
type="checkbox"
aria-label="Checkbox for following text input"
onChange={() => this.toggleDefault(prof._id)}
defaultChecked
/>
) : (
<input
name="defaultProfileCheck"
type="checkbox"
aria-label="Checkbox for following text input"
onChange={() => this.toggleDefault(prof._id)}
/>
)}
</td>
<td>
<button type="button" className="btn btn-warning">
Update
</button>
</td>
<td>
<button type="button" className="btn btn-danger">
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</React.Fragment>
);
}
toggleDefault - onChange
state = {
profilesData: []
};
async componentDidMount() {
const profiles = await getUserProfiles(); //Service Call
this.setState({ profilesData: profiles.data }); }
async toggleDefault(_id) {
if (window.confirm("Are you sure?")) {
try {
await setDefaultProfile(_id); //Service Call
} catch (ex) {
if (ex.response && ex.response.status === 404) toast.error(ex.message);
}
//toast.success("Done.");
const profiles = await getUserProfiles(); //Service call for get updated data
this.setState({ profilesData: profiles.data }); //Trying to setState for update view
} else {
}
}
谢谢。
【问题讨论】:
标签: javascript reactjs